Java 在泛型类型类中调用方法
假设我们有两个类A,B:Java 在泛型类型类中调用方法,java,generics,Java,Generics,假设我们有两个类A,B: class A extends SomeClass { public String getProp() { return "propA"; } } class B extends SomeOtherClass{ private String propB; public B setProp(String value) { propB = value; return this; } public
class A extends SomeClass {
public String getProp() {
return "propA";
}
}
class B extends SomeOtherClass{
private String propB;
public B setProp(String value) {
propB = value;
return this;
}
public String getProp() {
return propB;
}
}
假设我们有另一个类X,这个类X有一个方法someMethod引用这些类中的任何一个,有没有一种方法可以在这个方法中使用泛型来调用getProp()根据已传递的对象?泛型是为了编译时的类型安全,而不是为了在运行时实现多态性。所以我认为你的要求是不可能的
在你的场景中,你应该考虑创建一个接口。大概是这样的:
public interface PropInf{
String getProp();
}
然后,您必须在两个类中实现这个接口。使用此接口的引用变量,就可以实现多态性。不使用泛型
可以为这些类定义具有getProp()方法的公共接口。然后,使用它的方法应该接受接口的实例,并可以调用接口上的
getProp()
方法,该方法将由您传入的具体类实现。定义一个接口,如下所示:
interface StringPropProvider {
String getProp();
}
然后定义类以实现该接口:
class A extends SomeClass implements StringPropProvider {
public String getProp() {
return "propA";
}
class B extends SomeOtherClass implements StringPropProvider {
private String propB;
public B setProp(String value) {
propB = value;
return this;
}
public String getProp() {
return propB;
}
}
这算是个答案,但我不喜欢
public class X<T>{
public void someMethod(T t) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
t.getClass().getMethod("getProp", null).invoke(t, null);
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
X<A> weird = new X<>();
A a = new A();
weird.someMethod(a);
}
公共类X{
public void someMethod(T)抛出NoSuchMethodException、IllegalAccessException、IllegalArgumentException、InvocationTargetException{
t、 getClass().getMethod(“getProp”,null).invoke(t,null);
}
公共静态void main(字符串[]args)抛出NoSuchMethodException、IllegalAccessException、IllegalArgumentException、InvocationTargetException{
X=新的X();
A=新的A();
奇怪的方法(a);
}
}好吧,简短的回答是“不”。