用Java实例化泛型类我知道Java的泛型略低于.NET的泛型。我有个普通课Foo<T>,我真的需要实例化一个T在……里面Foo使用无参数构造函数。如何绕过Java的限制?
3 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
Bar.class
Class<T>
public class Test{ public static void main(String [] args) throws Exception // Just for simplicity! { Generic<Bar> x = new Generic<Bar>(Bar.class); Bar y = x.buildOne(); }}public class Generic<T>{ private Class<T> clazz; public Generic(Class<T> clazz) { this.clazz = clazz; } public T buildOne() throws InstantiationException, IllegalAccessException { return clazz.newInstance(); }}public class Bar{ public Bar() { System.out.println("Constructing"); }}
动漫人物
TA贡献1815条经验 获得超10个赞
public class Test { public static void main(String [] args) throws Exception { Generic g = new Generic(); g.initParameter(); }}import java.lang.reflect.ParameterizedType;public abstract class GenericAbstract<T extends Foo> { protected T parameter; @SuppressWarnings("unchecked") void initParameter() throws Exception, ClassNotFoundException, InstantiationException { // Get the class name of this instance's type. ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass(); // You may need this split or not, use logging to check String parameterClassName = pt.getActualTypeArguments()[0].toString().split("\\s")[1]; // Instantiate the Parameter and initialize it. parameter = (T) Class.forName(parameterClassName).newInstance(); }}public class Generic extends GenericAbstract<Foo> {}public class Foo { public Foo() { System.out.println("Foo constructor..."); }}
添加回答
举报
0/150
提交
取消