Java reflection snippets

get class from name:

Class c = Class.forName("my.own.class");

Examples

        //no paramater
	Class noparams[] = {};

	//String parameter
	Class[] paramString = new Class[1];	
	paramString[0] = String.class;

	//int parameter
	Class[] paramInt = new Class[1];	
	paramInt[0] = Integer.TYPE;

	try{
	        //get glass
		Class c = Class.forName("my.own.class");
                //get instance of a class
		Object obj = cls.newInstance();
                //get nested class
                Class cnested = Class.forName("my.own.class$myInnerClass");
                //get all nested classes
                Class[] nested = c.getDeclaredClasses();

                //call private method. could return "my.own.class" instance for singletons
                Method m = c.getDeclaredMethod("getInstance", noparams); 
                m.setAccessible(true);
                obj = m.invoke(null, null);
		//call method, no params
		Method m = c.getDeclaredMethod("myMethod", noparams);
		m.setAccessible(true);
                m.invoke(obj, null);

		//call method, pass String param 
		m = c.getDeclaredMethod("stringMethod", paramString);
                m.setAccessible(true);
		m.invoke(obj, new String("input data"));

		//call method, pass int param
		m = c.getDeclaredMethod("intMethod", paramInt);
                m.setAccessible(true);
		m.invoke(obj, 123456);

                //get field
                Field f = getDeclaredField("myVar");
                f.setAccessible(true);
                //get its value
                Object val = f.get(obj);
	}catch(Exception ex){
		ex.printStackTrace();
	}

 

 

 

links:

http://docs.oracle.com/javase/tutorial/reflect/

http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html