This question already has an answer here:
- Generic as method return type 1 answer
I am trying to do this
MyBean2 bean2 = MyBean.createBeanFrom();
Note: This is nothing like the other question because this is about the static method.
Is there a way to determine the actual class of return type at runtime ? My research so far indicates this is not possible. ("Erasures" & "Bridge Method" problems). However I don't give up and it would be cool to do the above stuff. Please provide a) solution if this is possible b) if not possible answer/thoughts as to why this capability does not exist c) why it does not make sense to have this capability
public class MyBean2 extends MyBean {}
public class MyBean3 extends MyBean {}
public class MyBean {
void tryingToDoThis() {
MyBean2 bean2 = MyBean.<MyBean2>createBeanFrom();
MyBean3 bean3 = MyBean.<MyBean3>createBeanFrom();
}
public static <T> T createBeanFrom() {
Class c = null;
MyBean newBean = null;
try {
Method m = MyBean.class.getMethod("createBeanFrom", new Class[] {});
java.lang.reflect.Type t = m.getGenericReturnType();
//c = ??;//How to determine this at runtime ?
newBean = (MyBean) c.newInstance();
newBean.init();//something
} catch (Exception e) {
e.printStackTrace();
}
return (T) newBean;
}
void init(){}
}
Aucun commentaire:
Enregistrer un commentaire