0

Let's say have a class name as string.

String myClass = "com.whatever.MyClass";

How can I instantiate this class using reflection and have an object of type MyClass and not Object, without using code like this:

MyClass myObj = MyClass.class.cast(instance);

Basically I want to convert an instance of Object to MyClass without using MyClass in code and just by knowing the class name as string.

kmata53
  • 13
  • 1
  • 1
  • You can't. In order to assign it to a reference of type `MyClass`, you need to know what `MyClass` is at compile time. – Andy Turner Apr 29 '16 at 13:37
  • And the only way to do it is http://stackoverflow.com/questions/2215843/using-reflection-in-java-to-create-a-new-instance-with-the-reference-variable-ty – Tunaki Apr 29 '16 at 13:39
  • You could look at the factory pattern, putting them into some kind of string-indexed container and calling them up. That's how it's done in C++, but I don't know about Java. –  Apr 29 '16 at 14:09

1 Answers1

0

You can create an instance of a class and run its methods without ever having to import the class in your code using reflection:

Class clazz = Class.forName("com.whatever.MyClass");
Object instance = clazz.newInstance();  // or use the given instance
clazz.getMethod("myMethod").invoke(instance);
Hok
  • 847
  • 8
  • 16