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.

3
  • You can't. In order to assign it to a reference of type MyClass, you need to know what MyClass is at compile time. Commented Apr 29, 2016 at 13:37
  • And the only way to do it is stackoverflow.com/questions/2215843/… Commented Apr 29, 2016 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. Commented Apr 29, 2016 at 14:09

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.