I am wondering if I can use the returned type of java's reflection method getReturnType() to create Objects of that type.
I have a method which returns a String, assume that we don't know that at run-time, so I call the getReturnType()
to determine what type of Objects the method returns:
Method myMethod = Book.class.getDeclaredMethod("printName");
Type myType = myMethod.getReturnType();
I am wondering if it is possible to use that myType
to create new Objects or how can I do that? I tried mytype something = new mytype();
but it is wrong.
First, the Method#getReturnType()
is declared as such
Class<?> java.lang.reflect.Method.getReturnType()
and the javadoc states that it
Returns a
Class
object that represents the formal return type of the method represented by thisMethod
object.
The Class
class provides a newInstance()
method which can use the no argument constructor to create an instance or you can use the Class#getDeclaredConstructors()
method to get a list of Constructor
instances and use their newInstance(Object...)
method to create an instance of the class represented.
You won't be able to create a variable of that type since the type is unknown at compile time.
Since the type itself is dynamic you can't declare a variable of that type, this because a declaration is a compile time feature.
Given that, you can istantiate an object of the returned type:
try {
Method myMethod = Book.class.getDeclaredMethod("printName");
Class<?> type = myMethod.getReturnType();
Object instance = type.newInstance();
}
catch (...) {
}
The problem is that you can't know the type variable of getReturnType()
returned Class
, you just know that this is a Class<?>
so there's no way to know statically the type of the instance generated by type.newInstance()
, hence you store it inside an Object
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.