方法在java中返回动态类型

Shr*_*kar 1 java generics

如何编写一个返回动态类型的方法(如果可以的话)

就像是

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
}
Run Code Online (Sandbox Code Playgroud)

然后我可以像使用它一样

HttpGet httpGet = createRequestObject(HttpGet.class , "http://wwww.google.com , "username","password");

or 

HttpPost httpPost = createRequestObject(HttpPost.class , "http://wwww.google.com , "username","password");
Run Code Online (Sandbox Code Playgroud)

我知道我可以返回一个对象,然后再投出它,但我不喜欢演员,所以想知道java中是否有一个可以帮助我做这个的构造

ζ--*_*ζ-- 12

简单地说,将方法声明为泛型,声明其返回类型及其类:

public <T> T foo(Class<T> clazz, Object... args) {
    return null;
} 
Run Code Online (Sandbox Code Playgroud)

显然,参数与人们所需要的不同.您可以使用以下命令实例化新T的:

clazz.newInstance();
Run Code Online (Sandbox Code Playgroud)

对于一个空的构造函数.

对于带参数的构造函数(在此示例中为String s和Object o):

return x.getConstructor(String.class, Object.class).newInstance("s", new Object());
Run Code Online (Sandbox Code Playgroud)

实际上,多亏了你的varargs,你可以遍历数组并获得构造函数查找所需的所有类对象.

然后你可以安全地做:

String s = foo(String.class, "a", "b");
Run Code Online (Sandbox Code Playgroud)

如果要将T约束为使用的子类HttpRequest:

public <T extends HttpRequest> T foo(Class<T> clazz, Object... args)
Run Code Online (Sandbox Code Playgroud)