import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest
{
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException
{
Foo foo = new Foo("1254");
Class aClass = foo.getClass();
//打印所有的方法名
Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++)
{
System.out.println("i=" + i + " " + methods[i].getName());
}
//得到某个非静态的隐藏方法
Method aMethod = null;//aClass.getMethod("getID", null);
aMethod = aClass.getDeclaredMethod("getID", null);
//私有方法需要设置
aMethod.setAccessible(true);
String result = "";
result = (String) (aMethod.invoke(foo, null));//参数中需要类对象
System.out.println("user id is " + result);
Method argsMethod = aClass.getMethod("setID",
new Class[] { String.class });
argsMethod.invoke(foo, new Object[] { "879" });
result = (String) (aMethod.invoke(foo, null));//参数中需要类对象
System.out.println("after setID user id is " + result);
//得到某个静态的隐藏方法
Class aClassForStaticMethod = Class.forName("Foo");
Method staticMethod = aClassForStaticMethod.getMethod("getUserID", null);
int intResult = (Integer) (staticMethod.invoke(null, null));//参数中不需要实例对象
System.out.println("intResult is " + intResult);
//得到所有的内部类
Class[] classes = aClassForStaticMethod.getClasses();
for (int i = 0; i < classes.length; i++)
{
System.out.println("i=" + i + " class name is "
+ classes[i].getName());
}
}
}
class Foo
{
private String id;
public Foo(String aID)
{
id = aID;
}
///** @hide */
private String getID()
{
return id;
}
/** @hide */
public void setID(String aId)
{
this.id = aId;
}
/** @hide */
public static int getUserID()
{
return 100;
}
///** @hide */
private static class InnerClass
{
public String getInnerClassString()
{
return ";lkdjtgpowei";
}
}
}
Java反射
最新推荐文章于 2024-09-24 08:39:48 发布