Casting a class using reflection in java

给你一囗甜甜゛ 提交于 2019-12-13 18:30:26

问题


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?


回答1:


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.




回答2:


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();



回答3:


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);



回答4:


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.



来源:https://stackoverflow.com/questions/17321521/casting-a-class-using-reflection-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!