Java 如何查找并返回<;的对象;派生类型>;在<;基本类型>;?
情景:Java 如何查找并返回<;的对象;派生类型>;在<;基本类型>;?,java,generics,reflection,Java,Generics,Reflection,情景: 我有一个Component类型的私有列表(其中Component是 抽象类) 此列表具有任意数量的不同组件子类 (其中每个派生类型在该列表中都是唯一的) 我想提供一种方法,允许用户找到 他们偏好的特定部分 我的尝试: private ArrayList<Component> components = new ArrayList<Component>(); public <T extends Component> T getComponent( T
- 我有一个Component类型的私有列表(其中Component是 抽象类)
- 此列表具有任意数量的不同组件子类 (其中每个派生类型在该列表中都是唯一的)
- 我想提供一种方法,允许用户找到 他们偏好的特定部分
private ArrayList<Component> components = new ArrayList<Component>();
public <T extends Component> T getComponent( T type )
{
for ( Component c : components )
{
if ( c instanceof T )
{
return (T) c;
}
}
return null;
}
private ArrayList components=new ArrayList();
公共T组件(T类型)
{
用于(组件c:组件)
{
if(T的c实例)
{
返回(T)c;
}
}
返回null;
}
编译器在if语句中报告以下错误:
无法对类型参数T执行instanceof check。请改用其擦除组件,因为运行时将擦除更多的泛型类型信息
实现此行为的推荐方法是什么?编译器非常清楚 改用它的擦除组件 您可以将参数
T type
替换为组件c
之后,您只需提取c的类型(它将是一个实现,因此c.getClass()将是一个扩展组件的类)
然后检查类型是否匹配并返回第一个元素
private ArrayList<Component> components = new ArrayList<Component>();
public <T extends Component> T getComponent( Component component )
{
for ( Component c : components )
{
if ( c.getClass().equals(component.getClass()) )
{
return c;
}
}
return null;
}
private ArrayList components=new ArrayList();
公共T getComponent(组件组件)
{
用于(组件c:组件)
{
如果(c.getClass().equals(component.getClass()))
{
返回c;
}
}
返回null;
}
我认为它应该很管用
我希望这对您有所帮助您可能需要依靠: 确定指定的对象是否与此类表示的对象兼容。此方法是Java语言
instanceof
运算符的动态等价物
提供类
实例而不是对象更有意义:
public <T extends Component> T getComponent(Class<T> type)
{
for (Component c : components) {
if (type.isInstance(c)) {
return (T) c;
}
}
return null;
}
publicGetComponent(类类型)
{
用于(组件c:组件){
if(类型isInstance(c)){
返回(T)c;
}
}
返回null;
}
为什么你认为它应该工作得很好?Type
应该是Class subclass
@LuiggiMendoza确实更有意义。这正是我想要的,非常感谢。在我最初的问题中,我可能没有完全弄清楚这一点,但我试图传入一个类类型作为参数(不是所述类的实例),这就是您的解决方案所实现的。再次感谢。你真的需要仿制药吗?使用类作为getComponent参数。与此公共组件一样,getComponent(类类型){for(组件c:components){if(c.getClass().equals(类型)){return c;}}return null;}
public <T extends Component> T getComponent(Class<T> type)
{
for (Component c : components) {
if (type.isInstance(c)) {
return (T) c;
}
}
return null;
}