Reputation: 1547
Suppose that we have 2 classes 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 String getProp() {
return propB;
}
}
and suppose that we have another class called X and this class X has a method someMethod that takes a reference to any of these classes ,is there a way that we can use generics in this method to call getProp() according to the object that has been passed?
Upvotes: 0
Views: 86
Reputation: 1547
Well this can be considered an answer , but I don't like it..
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);
}
}
Upvotes: 0
Reputation: 6783
Generics is meant for type-safety at compile time and not for achieving polymorphism at run-time. So I don't think what you're asking is possible.
In your scenario, you should consider creating an interface. Something like this:
public interface PropInf{
String getProp();
}
You would then have to implement this interface in both your classes. Using a reference variable of this interface, you can then achieve polymorphism.
Upvotes: 0
Reputation: 2294
Define an interface
as follows:
interface StringPropProvider {
String getProp();
}
then define your classes to implement that interface:
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;
}
}
Upvotes: 0
Reputation: 164341
Not using generics.
You can define a common interface for these classes that has the getProp() method. The method using it should then accept an instance of the interface, and can call the getProp()
method on the interface, which will be implemented by the concrete class you pass in.
Upvotes: 2