0

If we have class as shown below:

Class ClassA {

}

To create an instance of classA using reflection, we either get reference to the default constructor and invoke it or call Class.forName(".ClassA").newInstance()

The question is how do I achive the same thing for a class that takes generic type.

Say I have a class

 public class ClassA<T> implements IClassA<String, T> {

        public ClassA(Class<T> clazz) {
            super(clazz, clazz.getSimpleName());
        }
    }

If we want to create an instance of type ClassA we do the following:

ClassA<ClassB> object = new ClassA<>(ClassB.class);

So, If I know fully qualified class names for ClassA and ClassB, will I be able to create an instance at runtime.

Thanks for your help in advance...

-Chandra

  • [As a possible answer](http://stackoverflow.com/questions/6373800/use-reflection-to-create-a-generic-parameterized-class-in-java) – MadProgrammer Mar 13 '17 at 07:10
  • 1
    Generics in Java happen at compile time. They will have no effect on runtime things like reflection. In particular, the class name is the same as without a generic type and an instance of `ClassA` is indistiguishable from an instance of `ClassA`. If you need to refer to the generic type at runtime, the instance has to store an "evidence field". – Thilo Mar 13 '17 at 07:11
  • If I know the class and generic type, is there a way to create the class instance... – Chandra Pinjala Mar 13 '17 at 18:59

0 Answers0