http://www.verejava.com/?id=16995163767837
package com.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.TypeVariable;
public class TestMethod
{
/**
*
* @param args
*/
public static void testGetMethods()
{
try
{
Class c=Class.forName("com.entity.Student");
Method[] methods=c.getMethods();
for(Method method:methods)
{
System.out.println(method.getModifiers());
System.out.println(method.getName());
}
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void testGetDeclaredMethods()
{
try
{
Class c=Class.forName("com.entity.Student");
Method[] methods=c.getDeclaredMethods();
for(Method method:methods)
{
System.out.println(method.getModifiers());
System.out.println(method.getName());
}
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void testInvoke()
{
try
{
Class c=Class.forName("com.entity.Student");
Object obj=c.newInstance();
Method method=c.getMethod("setName",new Class[]{String.class});
method.invoke(obj,new Object[]{"王浩"});
method=c.getMethod("getName",null);
System.out.println(method.invoke(obj, null));
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void testInvokePrivate()
{
try
{
Class c=Class.forName("com.entity.Student");
Object obj=c.newInstance();
Method method=c.getDeclaredMethod("getHello",null);
method.setAccessible(true);
System.out.println(method.invoke(obj, null));
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
testInvokePrivate();
}
}
package com.entity;
public class Student
{
private String name;
private int age;
public Student()
{
super();
System.out.println("student");
}
public Student(String name, int age)
{
super();
this.name = name;
this.age = age;
System.out.println(this.name+","+this.age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
private String getHello()
{
return "hello";
}
}