将对象类型作为参数传递给方法?

Posted

技术标签:

【中文标题】将对象类型作为参数传递给方法?【英文标题】:Passing Object Type into method as a Parameter? 【发布时间】:2022-01-22 10:45:04 【问题描述】:

我有以下方法通过 Id 返回 Person 对象:

   private Person getPersonById(String client) 

    Person output = null;
    EntityManager entityManager = null;

    try 
        entityManager = entityManagement.createEntityManager(client);
        output = entityManager.find(Person.class, id);

     catch (Exception e) 
     
     // handle
    
     finally 
        entityManagement.closeEntityManager(client, entityManager);
    
    return output;

有没有办法让这个方法更通用,以便我可以传入其他对象类型,例如 Place , Cost 也是?请注意,它们不会继承相同的超类。

例如我应该通过吗? Person.class 作为方法参数等?

【问题讨论】:

【参考方案1】:

如果你想传入一个类对象并使你的方法通用,你可以这样做:

private <E> E getObjectById(String client, Class<E> cls) 

    E output = null;
    EntityManager entityManager = null;

    try 
        entityManager = entityManagement.createEntityManager(client);
        output = entityManager.find(cls, id);

     catch (Exception e) 
     
     // handle
    
     finally 
        entityManagement.closeEntityManager(client, entityManager);
    
    return output;

如果您将Person.class 作为cls 参数传递,它将等同于您的原始代码。

假设entityManager.find 将接受任何类并尝试返回该类的实例。

如果entityManager.find 对其接受的类的特征有一些限制,则需要在泛型类型参数&lt;E&gt; 中指定它们。

【讨论】:

以上是关于将对象类型作为参数传递给方法?的主要内容,如果未能解决你的问题,请参考以下文章