How do I pass a class as a parameter in Java?

JavaClassGwtParameters

Java Problem Overview


Is there any way to pass class as a parameter in Java and fire some methods from that class?

void main()
{
    callClass(that.class)
}

void callClass(???? classObject)
{
    classObject.somefunction
    // or 
    new classObject()
    //something like that ?
}

I am using Google Web Toolkit and it does not support reflection.

Java Solutions


Solution 1 - Java

public void foo(Class c){
        try {
            Object ob = c.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

How to invoke method using reflection

 import java.lang.reflect.*;

        
   public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }
        
      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

Also See

Solution 2 - Java

public void callingMethod(Class neededClass) {
    //Cast the class to the class you need
    //and call your method in the class
    ((ClassBeingCalled)neededClass).methodOfClass();
}

To call the method, you call it this way:

callingMethod(ClassBeingCalled.class);

Solution 3 - Java

Construct your method to accept it-

public <T> void printClassNameAndCreateList(Class<T> className){
    //example access 1
    System.out.print(className.getName());

    //example access 2
    ArrayList<T> list = new ArrayList<T>();
    //note that if you create a list this way, you will have to cast input
    list.add((T)nameOfObject);
}

Call the method-

printClassNameAndCreateList(SomeClass.class);

You can also restrict the type of class, for example, this is one of the methods from a library I made-

protected Class postExceptionActivityIn;

protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
    this.postExceptionActivityIn = postExceptionActivityIn;
}

For more information, search Reflection and Generics.

Solution 4 - Java

Use

void callClass(Class classObject)
{
   //do something with class
}

A Class is also a Java object, so you can refer to it by using its type.

Read more about it from official documentation.

Solution 5 - Java

This kind of thing is not easy. Here is a method that calls a static method:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

Solution 6 - Java

Adding <T> T as return type worked for me. Ex with json deserialize

 public static <T> T fromJson(String json, Class<T> classOfT){
     return gson().fromJson(json, classOfT);
 }

Solution 7 - Java

I am not sure what you are trying to accomplish, but you may want to consider that passing a class may not be what you really need to be doing. In many cases, dealing with Class like this is easily encapsulated within a factory pattern of some type and the use of that is done through an interface. here's one of dozens of articles on that pattern: http://today.java.net/pub/a/today/2005/03/09/factory.html

using a class within a factory can be accomplished in a variety of ways, most notably by having a config file that contains the name of the class that implements the required interface. Then the factory can find that class from within the class path and construct it as an object of the specified interface.

Solution 8 - Java

As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.

Solution 9 - Java

Se these: http://download.oracle.com/javase/tutorial/extra/generics/methods.html

here is the explaniation for the template methods.

Solution 10 - Java

Have a look at the reflection tutorial and reflection API of Java:

https://community.oracle.com/docs/DOC-983192[enter link description here]1

and

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html

Solution 11 - Java

Class as paramater. Example.

Three classes:

class TestCar {

	private int UnlockCode = 111;
	protected boolean hasAirCondition = true;
    String brand = "Ford";
	public String licensePlate = "Arizona 111";
}

--

class Terminal {
    
public void hackCar(TestCar car) {
     System.out.println(car.hasAirCondition);
     System.out.println(car.licensePlate);
     System.out.println(car.brand);
     }
}

--

class Story {

	public static void main(String args[]) {
		TestCar testCar = new TestCar();
		Terminal terminal = new Terminal();
		terminal.hackCar(testCar);
	}

}

In class Terminal method hackCar() take class TestCar as parameter.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser562350View Question on Stackoverflow
Solution 1 - JavajmjView Answer on Stackoverflow
Solution 2 - JavaOlanrewaju O. JosephView Answer on Stackoverflow
Solution 3 - JavaJoshua GaineyView Answer on Stackoverflow
Solution 4 - JavadariooView Answer on Stackoverflow
Solution 5 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 6 - JavazeurosView Answer on Stackoverflow
Solution 7 - JavaJorelView Answer on Stackoverflow
Solution 8 - JavaGursel KocaView Answer on Stackoverflow
Solution 9 - JavaHarold SotaView Answer on Stackoverflow
Solution 10 - JavaMarcus GründlerView Answer on Stackoverflow
Solution 11 - Javaromangorbenko.comView Answer on Stackoverflow