这是一个Java Generics程序,它使用set(T t),get()和print(T t)方法实现自定义接口.
我使用的类称为Animal.它需要一个T参数(在本例中为String)并为动物命名.
我的问题是我无法访问我的print函数中的任何Animal类方法.
Animal<String> a1 = new Animal();
a1.set("Mickey");
public void print(Object o) {
Animal oAnimal = (Animal) o; //Downcasting from Object to Animal.
System.out.println(o.get()); //not accessible, and I don't know how to make it accessible.
//I can only access the methods from Object, not my custom class called Animal.
}
Run Code Online (Sandbox Code Playgroud)
问题是你仍然试图调用方法o,它仍然是类型Object(就变量的编译时类型而言,这是编译器所关心的).
如果你打电话给方法oAnimal,那就没关系了:
System.out.println(oAnimal.get());
Run Code Online (Sandbox Code Playgroud)
(你不能返回结果System.out.println,因为它是一个void方法.你也不能为你的 void方法指定一个返回值.)
请注意,这与泛型无关.您可以使用String以下代码简单地演示您问题中的代码:
Object o = "foo";
String text = (String) o;
System.out.println(o.length()); // Error; Object doesn't have a length() method
System.out.println(text.length()); // Prints 3
Run Code Online (Sandbox Code Playgroud)
你(编辑)的问题确实说明了一个使用泛型的,但你投来Animal是强制转换为原始类型,因此它更简单刚刚离开仿制药的方程-为编辑失败的原因无关,与Animal被仿制.