0

I have been trying to instantiate a generic DAO class. The problem is that I have a Class<?> class. It can be Client or Worker, so I can't specify which class is it. I tried instantiating the DAO class with Class<?>, but the DAO wont work right since I am using reflection on DAO to find out the fields the class used in generics have.

I need to do something like this.

DAO dao = new DAO<this.gerindo.getClass()>();
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Post what you tried, and what error you got – Jesse Barnum Nov 06 '22 at 17:22
  • 1
    You certainly cannot do generics like that. You will probably need to use a raw type, or use generics more carefully, e.g. having your `gerindo` object have an appropriate generic method doing the job for you. You haven't given us enough information that we can tell you how that would work – Louis Wasserman Nov 06 '22 at 17:28
  • 1
    You can't do this, and it would irrelevant, because the type parameter is not available at runtime due to erasure of generic types, so it would be the same as the raw-type `new DAO()` (not to mention you assign it to a variable with a raw type. If the class provided any useful information here, you would also need to pass the Class instance to the constructor. – Mark Rotteveel Nov 06 '22 at 17:29

1 Answers1

0

basically, you can't do that. Even if you could, your dao object would be generic (no type as parameter) and not very helpful. For instance, you would have to cast the return value of a findById method since the type is not known at compile time.