method returning dynamic type in java
generics, java
Solution
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)
Problem
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