【问题标题】: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 作为方法参数等?

【问题讨论】:

    标签: java class generics predicate nhibernate-criteria


    【解决方案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; 中指定它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2015-11-22
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多