Java 接受菱形运算符值的自定义函数
我在C中看到了这一点:Java 接受菱形运算符值的自定义函数,java,Java,我在C中看到了这一点: this.addComponent<MyClass>(); 我该如何使用这样的方法呢?我试着这样做: public Component addComponent<T>(){ return new Component(); } 但它不起作用。甚至有可能做出这样的事情吗?听起来像是你在问,尽管我不完全清楚你想做什么 public <T extends Component> T addComponent(Class<T>
this.addComponent<MyClass>();
我该如何使用这样的方法呢?我试着这样做:
public Component addComponent<T>(){
return new Component();
}
但它不起作用。甚至有可能做出这样的事情吗?听起来像是你在问,尽管我不完全清楚你想做什么
public <T extends Component> T addComponent(Class<T> clazz) {
return clazz.newInstance();
}
将允许您传入任何类对象,并返回相同类型的对象
其次,请注意,如果希望将实例作为参数而不是更典型的用例类对象传入,则会自动推断其类型:
public <T> T doStuff(T input){
input.doStuff(); // does stuff to T instance
return input; //return value is of type T
}
另外,我假设您知道Class.newInstance抛出InstantiationException,尽管上面的代码中没有反映这一点这在C中有效,因为C已经具体化了泛型,即您可以在运行时发现泛型类型参数是什么。在Java中不能这样做,因为Java在运行时忽略类型参数,而只在编译时将其用于类型检查。考虑将类对象作为参数传递给方法,谢谢,我稍后再看一看!所以要调用上面的类,应该是this.addComponentTestComp.class,对吗?好的,谢谢!我希望它看起来像C的方式,它看起来更干净。哦,好吧,它似乎在做我想做的事情!
public <T> T doStuff(T input){
input.doStuff(); // does stuff to T instance
return input; //return value is of type T
}
public <T extends Component> T doStuff(T input){
T t = new T(); // NO!
T.someStaticMethod(); // NO!
return (T) new Component(); //hacky, but OK
}