0

Below is running fine:

ResultSetHandler<List<MyClass>> h = new BeanListHandler<MyClass>(MyClass.class);

Issue is that MyClass is hard-coded. Above line is at centralized location and hence hard-coding is bad.

I have fully qualified class name of MyClass i.e. com.company.vo.MyClass

Now I want to generate above ResultSetHandler by converting incoming String to actual class.

Please help, I have tried:

Class<?> classObj = Class.forName("com.company.vo.MyClass");
ResultSetHandler<List<classObj>> h = new BeanListHandler<classObj>(classObj.class);

Which throws:

classObj cannot be resolved to a type

Thanks for reading.

Nikhil Joshi
  • 817
  • 2
  • 12
  • 34
  • You can't do that. Generics have no business at runtime. You've to know the class name at compile time. – Rohit Jain Mar 12 '15 at 09:43
  • 1
    As Rohit Jain points out, that's not possible. Compiler needs to know the exact class at compile time. Alternative: `ResultSetHandler>` should work for your purpose, although not type-safe. – m0skit0 Mar 12 '15 at 09:47
  • 1
    What @RohitJain was reffering to is called *type erasure*. Look at this link: [Type Erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html) – riccardo.cardin Mar 12 '15 at 09:50
  • I'm not sure whether type erasure is an issue here. What does `query.getResultMapperClass()` return *exactly*, and what is the error message *exactly*? The call should probably be `new BeanListHandler<...>(classObj) ` (without the `.class`) anyhow. – Marco13 Mar 12 '15 at 10:05
  • Maybe guarantee that the class implements a given interface `IFoo`. Then have `Class extends IFoo> classObj = ...`. Then you can do `ResultSetHandler> h = new BeanListHandler>(classObj);`. Having `IFoo` contain all of the methods that exist in the class that you expect. – Oli Mar 12 '15 at 10:09

1 Answers1

0

Hardcoded types are not bad. They are the essence of generics. The purpose of generics is to provide a better type check at compile time. If you want to use ResultSetHandler with lists of different types, think about to use a common base class or interface of these types.

Gren
  • 1,850
  • 1
  • 11
  • 16