我试图使一个类似于UnityEngine的Java组件系统,并希望构建一个通用的GetComponent()方法。尝试返回找到的类型时我陷入困境
public <T> T GetComponent (){
for (Component c: this.components){
//I know this doesn't work, I want to know how to check if the type
//matches and return it (ie. Collider col = GetComponent<Collider>();)
if(c == T)){
System.out.println("Component of type: " + c.name + " found!");
return T;
}
}
System.out.println("No component found");
return null;
}
感谢所有回答。这是关于Java和C#的区别的学习经历。
答案 0 :(得分:2)
您不能return T
。返回使用表达式,而不是类型。 return T
与return String
相似,无效。
您正试图返回一个组件,所以可能:
public <T> T GetComponent (Class<T> compnentType)
for (Component c: this.components){
if(c.getClass() == compnentType)){ //you need to check your logic here
System.out.println("Component of type: " + c.name + " found!");
return (T) c;
}
}
return null; //again, logic to be checked.
}
这将检查组件类。您不能在不接收组件类的情况下检查类型,因为您不能在T
检查中使用类型参数instanceof
。
答案 1 :(得分:1)
当我尝试从您的文本和代码中推断出您要实现的目标时,则看不到需要使用泛型。
在我看来,您似乎正在尝试实现这一目标:
public Component getComponent (){
for (Component c: this.components){
//I know this doesn't work, I want to know how to check if the type
//matches and return it (ie. Collider col = GetComponent<Collider>();)
if(c instanceof Collider) {
System.out.println("Component of type: " + c.name + " found!");
return c;
}
}
System.out.println("No component found");
return null;
}
即在集合中搜索Collider类型的实例。如果这个假设是正确的,则您的方法可以简化为单一方法:
public Collider getCollider (){
return components.stream().filter(c -> c instanceof Collider).findFirst().orElse(null);
}
编辑
下面来自@EpicNicks的评论,这是我的建议的改编:
public <T extends Component> T getComponent (Class<T> componentClass){
for (Component c: this.components){
//I know this doesn't work, I want to know how to check if the type
//matches and return it (ie. Collider col = GetComponent<Collider>();)
if(c.getClass().isAssignableFrom(componentClass)) {
System.out.println("Component of type: " + c.getClass().getSimpleName() + " found!");
return (T) c;
}
}
System.out.println("No component found");
return null;
}
答案 2 :(得分:0)
我现在无法检查此内容,但是也许可以在不传递参数的情况下完成找到正确类型的操作:
public <T> T GetComponent () {
for (Component c: this.components){
try {
return (T) c;
} catch (ClassCastException cce) {}
}
return null;
}
}