How do I pass a class as a parameter in 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
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);
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.