我有一个功能如下:
public boolean delete(int id) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.remove(em.find(Student.class, id));
em.getTransaction().commit();
return true;
}
现在我希望上述函数是一个通用函数。所以我通过以下方式实现了相同的:
public boolean genericDelete(int id, Object ob) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.remove(em.find((Class) ob, id));
em.getTransaction().commit();
return true;
}
该函数工作正常,没有任何缺陷,但 IntellijIDEA 提示对象被转换为类。这可能是一种不好的做法,那么如何以正确的方式实现呢?请帮忙...
最佳答案
不需要在那里 Actor 。 Java为此提供了直接的方法。
Class c = ob.getClass();
Oracle 文档:Retrieving Class Objects
If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass(). Of course, this only works for reference types which all inherit from Object. Some examples follow.
Class c = "foo".getClass();
关于java - 如何在 Hibernate 删除操作中获取对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594444/