我正在尝试制作一个类似于 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# 差异的学习经历。
最佳答案
您不能返回 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.
}
这会检查组件类。您无法在未接收组件类的情况下检查类型,因为您无法在 instanceof
检查中使用类型参数 T
。
关于Java 通用 GetComponent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51979206/