package com.wxjaa; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class TestReflect { public static void main(String[] args) throws Exception { // getDeclaredField 可以获取私有成员, getField只能获取公共成员 User u = new User(); System.out.println(u.getClass().getCanonicalName());// 获取类名 Constructor>[] cons = u.getClass().getDeclaredConstructors();// 构造器 for(Constructor> con : cons){ System.out.println(con.getName()); } Method[] methods = u.getClass().getDeclaredMethods();// 反射获取成员方法 Method.setAccessible(methods, true); for(Method method : methods){ if(method.getName().equals("test")){ method.invoke(u, "user2", 11);// 调用成员方法 } } System.out.println("--------- 获取部分成员 ---------"); String[] names = new String[]{"no","name"}; for(String name : names){ Field field = u.getClass().getDeclaredField(name); field.setAccessible(true);// 设置可以获取私有成员 System.out.println(name + ":" + field.get(u)); } System.out.println("--------- 获取全部成员 ---------"); Field[] fields = u.getClass().getDeclaredFields(); Field.setAccessible(fields, true);// 设置可以获取私有成员 for(Field field : fields){ System.out.println(field.getName() + ":" + field.get(u)); } } } class User { public long no; private String name; private int age; private boolean sex; public User(){ no = 123456l; name = "user1"; age = 25; sex = true; } public void test(String name, int age){ System.out.println(name + "," + age); } public long getNo() { return no; } public void setNo(long no) { this.no = no; } 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; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } }