173

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.

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117

11 Answers11

156
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

Mark Cramer
  • 2,614
  • 5
  • 33
  • 57
jmj
  • 237,923
  • 42
  • 401
  • 438
  • and how do i fire default constructor or some methods in that class ? –  Feb 02 '11 at 10:04
  • sorry i forgot to add about google web tool kit and stuff , im using google web toolkit and it doesnt support reflection . –  Feb 02 '11 at 10:12
  • 1
    Look at [here](http://gwtreflection.sourceforge.net/) and [here](http://stackoverflow.com/questions/451658/gwt-dynamic-loading-using-gwt-create-with-string-literals-instead-of-class-lite) also [this](http://stackoverflow.com/questions/4195233/can-you-use-java-reflection-api-in-gwt-client) – jmj Feb 02 '11 at 10:16
  • I wanna talk about the philosophy! Is Class a data type in Java? – Milad Rahimi Oct 27 '15 at 15:35
49
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);
  • The asker also wanted to use the class' constructor. That's not easy, and no one is addressing it here. This post provides an option (read all the comments, because the accepted answer doesn't work): https://stackoverflow.com/questions/234600/can-i-use-class-newinstance-with-constructor-arguments. It's pretty messy, though, and the compiler warnings you get suggest they didn't want people to do this with Java. Much easier in Python : ) – Andrew Puglionesi Nov 01 '18 at 23:40
28

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.

Joshua Gainey
  • 311
  • 3
  • 4
3

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.

darioo
  • 46,442
  • 10
  • 75
  • 103
3

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);
 }
zeuros
  • 71
  • 4
2

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
1

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.

Jorel
  • 153
  • 2
  • 14
0

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.

Gursel Koca
  • 20,940
  • 2
  • 24
  • 34
-1

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

here is the explaniation for the template methods.

Harold Sota
  • 7,490
  • 12
  • 58
  • 84
-1

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

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

and

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

Nelda.techspiress
  • 643
  • 12
  • 32
Marcus Gründler
  • 945
  • 13
  • 16
  • OP clearly stated he is using GWT which does not support reflection – Knarf Jul 02 '18 at 10:13
  • 2
    The question was edited long after my answer. The original question didn't contain that hint. The accepted answer is also referring to reflection by the way. – Marcus Gründler Jul 05 '18 at 11:50
-2

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.