Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java generic method Cannot resolve method 'getX()' in 'T'

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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*/;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading