An instance of any class as a method input in java

public class Class{
   public void method(class a, class b){
      //some stuff
   }
}

I want aand bcould be instances of any class. Is this legal in java? Is there any way to do this?

Thank.

+4
source share
3 answers

Use object. Any class in Java is a (direct or indirect) subclass of Object.

public class MyClass {
   public void method(Object a, Object b){
      //some stuff
   }
}

Oh, and do not use the class name "Class". It is already used in Java.

+9
source

Your given code is not legal because it classis a keyword in java, see JLS 3.9. Keywords

USe can use the class Objectfrom JLS 4.3.2. Class object

The class Object is the superclass (Β§8.1.4) of all other classes.

Use the following:

public class Class{
   public void method(Object a, Object b){
      //some stuff
   }
}
+5

:

public class Class{
   public <T1, T2> void method(T1 a, T2 b){
      //some stuff
   }
}

- - , , , :

public class Class{
   public <T1, T2> Map<T1, T2> toMap(T1 key, T2 val){
      Map<T1, T2> out = new HashMap<>();
      out.put(key, value);
      return out;
   }
}
+4

All Articles