方法在java中返回动态类型 [英] method returning dynamic type in java
问题描述
如何写一个方法(如果有的话)会返回一个动态类型
类似于
public X createRequestObject(Class xclass,String url,String username,String password){
X x = Class.forName(xclass.getCannonicalName())。getConstructor String.class).newInstance(URL);
x.setheader(AUTHORIZATION,createHeader(username,password)
return x
}
,然后我可以像使用它一样使用它。
HttpGet httpGet = createRequestObject(HttpGet.class,http ://wwwww.google.com,username,password);
或
HttpPost httpPost = createRequestObject(HttpPost.class,http:// wwww .google.com,username,password);
我知道我可以返回一个对象然后抛出它,但我不喜欢演员,所以想知道是否有一个构造在Java中,可以帮助我做到这一点
简单,将该方法声明为泛型,声明它的返回类型及其类: public< T> T foo(Class< T> clazz,Object ... args){
return null;
}
<显然这些参数是不同的,你可以用下面的方法实例化一个新的 T
:
clazz.newInstance();
为无效构造函数。
一个带参数的构造函数(在本例中是String s和Object o):
return x.getConstructor(String.class,Object。 class).newInstance(s,new Object());
事实上,感谢您的可变参数,您可以遍历数组并获取所有必需的类对象
然后你就可以安全地做:
字符串s = foo(String.class,a,b);
如果您想将T限制为 HttpRequest $的子类c $ c> use:
public< T extends HttpRequest> T foo(Class< T> clazz,Object ... args)
How can I write a method (if at all i can) that would return a dynamic type
something like
public X createRequestObject(Class xclass , String url , String username , String password){
X x = Class.forName(xclass.getCannonicalName()).getConstructor(String.class).newInstance(url);
x.setheader("AUTHORIZATION" , createHeader(username,password)
return x
}
and then i can use it like
HttpGet httpGet = createRequestObject(HttpGet.class , "http://wwww.google.com , "username","password");
or
HttpPost httpPost = createRequestObject(HttpPost.class , "http://wwww.google.com , "username","password");
I know i can return an object and then cast it later but i dislike casts so wondering if there is a construct in java that can help me do this
Simply, declare the method as generic, declare its return type, and its class:
public <T> T foo(Class<T> clazz, Object... args) {
return null;
}
Obviously the parameters are different that what one would need. You can instantiate a new T
with:
clazz.newInstance();
for a nullary constructor.
For a constructor with arguments(in this example String s and Object o):
return x.getConstructor(String.class, Object.class).newInstance("s", new Object());
In fact, thanks to your varargs you can iterate through the array and get all necessary class objects for the constructor lookup.
You can then safely do:
String s = foo(String.class, "a", "b");
If you want to constrain T to be a subclass of HttpRequest
use:
public <T extends HttpRequest> T foo(Class<T> clazz, Object... args)
这篇关于方法在java中返回动态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!