Search code examples
javagenericscastingsuperclass

Method taking an Object and any of its superclasses


To achieve.

A method signal should take

  1. any Object N
  2. any of the Object's superclasses Class<?super N>
<N>void
signal(N n, Class<?super N> n_super)
{
  /*...*/
}

It should be ok to call

Object object=new Object();
signal(object, object.getClass());

since Object is a super type of object. But calling it gives a waring. In IDE words:

IntelliJ (Android Studio)

Wrong 2nd argument type. Found Class<? extends Object>, required: Class<? super Object>

Eclipse

The method signal(N, Class<? super N>) is not applicable for the arguments (Object, Class<? extends Object>)

Questions.

  1. Can the goal be achieved, the way I have tried, and if yes,
  2. how can the warning be eliminated

Solution

  • Turning my comments into an answer.

    Two approaches I can quickly think of:


    Use Object.class directly here. signal(object, Object.class); compiles fine with no warnings on my java version.


    Change your method signature to something like:

    <N, M extends N> void signal(N n, Class<? super M> n_super)
    

    which should let you call it the way you already are (as in signal(object, object.getClass());).