1

I have a function as follows:

public boolean delete(int id) {

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.remove(em.find(Student.class, id));
    em.getTransaction().commit();

    return true;
}

Now i want the above function to be a generic one. So i implemented the same in the following way:

 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;
 }

The function is working without any flaw but IntellijIDEA complains about object being casted to Class. It might be a bad practice, so how to implement the same in a proper manner. Please help...

sam
  • 1,800
  • 1
  • 25
  • 47

1 Answers1

1

No need for cast there. Java gave a direct way for it.

Class c = ob.getClass();

Oracle docs : 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();
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Your solution works but IntellijIdea says Unchecked Assignment: java.lang.Class to java.land.Class – sam Feb 03 '18 at 06:13
  • 1
    @SAM It's ok in this case. Suppress it. https://stackoverflow.com/questions/509076/how-do-i-address-unchecked-cast-warnings – Suresh Atta Feb 03 '18 at 06:18