围绕Java中的Generics主题,我有一个问题:假设我在类中遵循泛型(静态)方法。在这种方法中,我想要访问实类的某些方法/字段。在静态语言Java中有什么类型错误的方法吗?或者有什么解决办法?
public class GenericClassUtil {
public static <T> void workWithRealTypeAttr(T objectClass) {
//here get access to values of Easel, Cat, Dog or some other class
}
}在主要代码中:
GenericClassUtil.workWithRealTypeAttr(new Easel());
GenericClassUtil.workWithRealTypeAttr(new Cat());
GenericClassUtil.workWithRealTypeAttr(new Dog());发布于 2014-08-18 08:52:12
创建一个接口并将Easel、Cat、Dog类扩展到该接口。
public static <T extends ThatInterface> workWithRealTypeAttr(T objectClass) {
//here get access to values of Easel, Cat, Dog or some other class
}参考:
有时,您可能希望限制可用作参数化类型中的类型参数的类型。例如,对数字进行操作的方法可能只希望接受Number的实例或其子类。这就是有界类型参数的用途。 若要声明有界类型参数,请列出类型参数的名称,后面跟着extends关键字,然后是其上限,在本例中,上限是Number。请注意,在这种情况下,扩展在一般意义上被用来表示“扩展”(如在类中)或“实现”(如在接口中)。
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public <U extends Number> void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.set(new Integer(10));
integerBox.inspect("some text"); // error: this is still String!
}
}发布于 2014-08-18 08:50:39
如果将泛型类型限制为扩展特定基类的类,则可以这样做。
例如,如果您的方法仅在Animal类上操作,那么您将拥有:
public static <T extends Animal> workWithRealTypeAttr(T objectClass) {
objectClass.someAnimalMethod()
}
public class Animal {
public void someAnimalMethod() {
}
}Easel、Cat和Dog的每一个成员都必须扩展Animal。试图使用不扩展workWithRealTypeAttr的参数调用Animal将导致编译时间错误。
当然,您可以通过使用接口而不是类来提供更多的灵活性。仿制药会以完全相同的方式工作。
您将只有一个接口Animal,类Easel、Cat和Dog将实现该接口。
注意事项
正如@user3218114非常正确地指出的那样,在这种简单的情况下不需要使用泛型。您可以使用Animal作为workWithRealTypeAttr的参数。但是我没有发布这个答案,因为我想向OP展示泛型在他/她提出的情况下是如何工作的。如果该方法适用于Collection或其他可以充分利用泛型的方法,则解决方案显然更适用。
发布于 2014-08-18 08:54:21
我想要访问实类的某些方法/字段。
如果要访问实际类的方法/字段,则使用不同的重载方法
class GenericClassUtil {
public static void workWithRealTypeAttr(Bird objectClass) {
// call a method specific to Bird (Easel)
}
public static void workWithRealTypeAttr(Mammal objectClass) {
// call a method specific to Mammal (Cat, Dog etc)
}
} 您可以将类分组为Mammal、Bird,并使该方法更加通用。

您可以根据设计模式的行为对类进行分组。
class GenericClassUtil {
public static void workWithRealTypeAttr(Flyable objectClass) {
// call a method specific to Flyable
}
public static void workWithRealTypeAttr(Swimmable objectClass) {
// call a method specific to Swimmable
}
}
interface Swimmable { public void swim() }
interface Flyable { public void fly() }

最好用头第一设计模式来解释
https://stackoverflow.com/questions/25359358
复制相似问题