rgksugan
rgksugan

Reputation: 3582

Casting a class using reflection in java

I have the following classes.

abstract class A{}

class B extends A{}

class C extends A{}

I need to create an object like this

A a = new B();

I get the class name of the subclass at runtime. So, I need to use reflection to create an object.

I have done this.

Class<?> klass = Class.forName(className);

Now I am not able to cast this class to the subclass.

I want to achieve

A a = klass.newInstance(); // returns Object

I want the object to be casted into the subclass (either B or C, decided on runtime)

How do I do this?

Upvotes: 1

Views: 11335

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200148

You can use Generics to declare

Class<? extends A> klass;

then you'll be allowed to write

A a = klass.newInstance();

However, since Class.forName has no type information on your class, and has no type inference declared, you'll be getting "unchecked cast" warnings. This approach is no more typesafe than just downcasting the result of the second line to A.

Upvotes: 3

Aleks G
Aleks G

Reputation: 57316

To follow up on the comments, you can create your instance of the class with either

Class klass = Class.forName(className);
A a = (A)klass.newInstance();

or

Class<? extends A> klass = Class.forName(className);
A a = klass.newInstance();

Then you can invoke a method on it with:

klass.getMethod(methodName, null).invoke();

Or, if the method takes arguments (e.g. int and String)

int param1 = ...;
String param2 = ...;
klass.getMethod(a, new Class[] { Integer.class, String.class }).invoke(param1, param2);

Of course, you'll need to be catching appropriate exceptions.

Upvotes: 0

Grzegorz Żur
Grzegorz Żur

Reputation: 49171

Having klass object of type Class<T> you can call Class.cast() method to cast to type T using

klass.cast(object)

For example, you have a of type B, you cast a to type B loaded at runtime.

Class<?> klass = Class.forName("B");
klass.cast(a);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500395

I want the object to be casted into the subclass (either B or C, decided on runtime)

That makes no sense. Casting is something which is primarily a compile-time operation, to end up with an expression of the appropriate type. It's then verified at execution time.

If you're really trying to achieve a variable of type A, then you only need to cast to A:

A a = (A) klass.newInstance();

Upvotes: 2

Related Questions