Say I have a couple of Objects (=classes) which each has a method getX():
public class A{
/* some code */
public float getX(){}
}
public class B{
/* some code */
public float getX(){}
}
Now I want to write a generic static method as the following:
public static <T> boolean isOverlaps(T obj) {
if (obj == null || (!obj.getClass().isInstance(A.class) && !obj.getClass().isInstance(B.class)))
return false;
return obj.getX() >= 0 && /*some logic*/; // here it falls
}
IDE says:
Cannot resolve method ‘getX()’ in ‘T’
How can I resolve the method properly without casting (since it is a generic method)? Is it even possible?
>Solution :
You need an interface to let Java know that T has the desired function:
public interface I {
float getX();
}
public class A implements I {
/* some code */
public float getX(){
return 1.0f;
}
}
public class B implements I {
/* some code */
public float getX(){
return 2.0f;
}
}
public static <T extends I> boolean isOverlaps(T obj) {
return obj.getX() >= 0 && /*some logic*/;
}
Or, a bit simpler without the unnecessary type variable:
public static boolean isOverlaps(I obj) {
return obj.getX() >= 0 && /*some logic*/;
}