【发布时间】:2016-10-06 13:22:57
【问题描述】:
所以我有一个有趣的问题...... 我想访问从 List 中检索到的对象的方法,该对象由 ArrayList 扩展。
看起来像这样:
import java.util.ArrayList;
import java.util.Collection;
public class PropertyList<Property> extends ArrayList {
private static final long serialVersionUID = -7854888805136619636L;
PropertyList(){
super();
}
PropertyList(Collection<Property> c){
super(c);
}
boolean containsProperty(PropertyList<Property> pl){
Property asdf = (Property) this.get(4);
System.out.println(asdf.<can't access "Property" methods>); //mark
return false;
}
}
知道为什么我不能访问标记行中的方法吗? 澄清一下 - Property 对象中的方法是公共的。
编辑: 属性说明:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
class Property {
@XmlValue
private String property = null;
@XmlAttribute
String state;
@XmlAttribute
String name;
@XmlAttribute
String type;
@XmlAttribute
String value;
Property(){}
Property(String state, String name, String type, String value){
this.state = state;
this.name = name;
this.type = type;
this.value = value;
}
public String getName(){
return name;
}
@Override
public String toString(){
return state + " " + name + " " + type + " " + value;
}
}
【问题讨论】:
-
你不应该
extends ArrayList<Property>吗?无论如何,您不能也显示Property的代码吗? -
@Shark 确实如此。就目前而言,这没有任何意义。然而,对
Property的显式转换让我也想看看定义:) -
无论如何,你的类声明不应该是这样的:
public class PropertyList<T> extends ArrayList<T>,你可以轻松地将T硬编码为Property? -
您没有投射到类属性。您正在转换为 PropertyList 类的泛型类型,您选择将其命名为 Property 而不是 T 或 E 或任何其他传统的单个字母,因此会影响 Property 类。您几乎不应该扩展集合类。在这种情况下当然不是。
-
好的,然后尝试按照我所说的(使用泛型类型)声明@JBNizet 指出的正确,它被遮蔽了。 (我猜
Property在这种情况下就像一个泛型类型,类似于T或E或GenericType可能是任何东西)而不是你具体的Property类。