package com.example;
public class Student {
// 变量和setAge、getAge方法都是私有的
private String id, name, sex;
private int age;
private final static String CLASSNAME = "Student";
private void setAge(int age) {
this.age = age;
}
private void getAge() {
System.out.println("age---" + age);
}
// test方法是公有
public void test(int i, int j) {
System.out.println("result---" + (i + j));
}
}
package com.example;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class class1 = Class.forName("com.example.Student");
// 或者Class class1 = Student.class;
// 获取所有的变量,包括私有
Field[] fields = class1.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
// System.out.println(fields[i].getType());
System.out.println(Modifier.toString(fields[i].getModifiers())
+ " " + fields[i].getType().getSimpleName() + " "
+ fields[i].getName());
}
// 获取所有的方法,包括私有
Method[] methods = class1.getDeclaredMethods();
StringBuilder parameterTypeBuilder;
for (int i = 0; i < methods.length; i++) {
parameterTypeBuilder = new StringBuilder(" ");// 为了美观,参数开始、结束加个空格
Class[] classes = methods[i].getParameterTypes();
for (int j = 0; j < classes.length; j++) {// 方法参数类型
if (classes.length > 1) {
parameterTypeBuilder.append(classes[j].getSimpleName()
+ " ");
} else {
parameterTypeBuilder.append(classes[j].getSimpleName()
+ " ");
}
}
boolean result = isEmpty(parameterTypeBuilder.toString());
System.out.println(Modifier.toString(methods[i].getModifiers())
+ " "
+ methods[i].getReturnType().getSimpleName()
+ " "
+ methods[i].getName()
+ ((result) ? "()" : "("
+ parameterTypeBuilder.toString() + ")"));
parameterTypeBuilder = null;
}
// 调用私有属性
Student student = (Student) class1.newInstance();// 强转对象
Field ageField = class1.getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(student, 24);// 设置 age值
// 调用私有方法
Method getAgeMethod = class1.getDeclaredMethod("getAge");
getAgeMethod.setAccessible(true);
getAgeMethod.invoke(student);// 调用getAge
//调用私有方法setAge修改值,再打印
Method setAgeMethod = class1.getDeclaredMethod("setAge",int.class);// 调用setAge,该方法有参数
setAgeMethod.setAccessible(true);
setAgeMethod.invoke(student,28);// 设置age
getAgeMethod.invoke(student);// 调用getAge
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static boolean isEmpty(String text) {
if ("".equals(text) || null == text) {
return true;
}
return false;
}
}