1.使用反射获取类的信息
创建实体类
public class FatherClass {
public String mFatherName;
public int mFatherAge;
public void printFatherMsg(){}
}
public class SonClass extends FatherClass{
private String mSonName;
protected int mSonAge;
public String mSonBirthday;
public void printSonMsg(){
System.out.println("Son Msg - name : "+ mSonName + "; age : " + mSonAge);
}
private void setSonName(String name){
mSonName = name;
}
private void setSonAge(int age){
mSonAge = age;
}
private int getSonAge(){
return mSonAge;
}
private String getSonName(){
return mSonName;
}
}
1.1获取类的所有变量信息
private static void printFields(){
Class mClass = SonClass.class;
System.out.println("类的名称:" + mClass.getName());
Field[] fields = mClass.getFields();
for (Field field :fields) {
int modifiers = field.getModifiers();
System.out.print(Modifier.toString(modifiers) + " ");
System.out.println(field.getType().getName() + " " + field.getName());
}
}
1.2获取类的所有方法信息
private static void printMethods(){
Class mClass = SonClass.class;
System.out.println("类的名称:" + mClass.getName());
Method[] mMethods = mClass.getMethods();
for (Method method : mMethods) {
int modifiers = method.getModifiers();
System.out.print(Modifier.toString(modifiers) + " ");
Class returnType = method.getReturnType();
System.out.print(returnType.getName() + " " + method.getName() + "( ");
Parameter[] parameters = method.getParameters();
for (Parameter parameter:parameters) {
System.out.print(parameter.getType().getName() + " " + parameter.getName() + ",");
}
Class[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0){
System.out.println(" )");
}
else {
for (Class c : exceptionTypes) {
System.out.println(" ) throws " + c.getName());
}
}
}
}
2.访问类的私有变量和方法
2.1访问私有方法
public class TestClass {
private String MSG = "Original";
private void privateMethod(String head , int tail){
System.out.print(head + tail);
}
public String getMsg(){
return MSG;
}
}
private static void getPrivateMethod() throws Exception{
TestClass testClass = new TestClass();
Class mClass = testClass.getClass();
Method privateMethod = mClass.getDeclaredMethod("privateMethod", String.class, int.class);
if (privateMethod != null) {
privateMethod.setAccessible(true);
privateMethod.invoke(testClass, "Java Reflect ", 666);
}
}