0%
获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class ReflectGet { public static void main(String[] args) throws NoSuchMethodException { Class c = Person.class;
System.out.println("c.getName() = " + c.getName()); System.out.println("c.getSimpleName() = " + c.getSimpleName());
Field[] fields = c.getFields(); for (Field field : fields) { System.out.println("field = " + field); } fields = c.getDeclaredFields(); for (Field field : fields) { System.out.println("declaredField = " + field); }
Method[] methods = c.getMethods(); for (Method method : methods) { System.out.println("method = " + method); } methods = c.getDeclaredMethods(); for (Method method : methods) { System.out.println("method = " + method); } Method method = c.getMethod("setAge", int.class); System.out.println("method = " + method);
Constructor[] constructors = c.getConstructors(); for (Constructor constructor : constructors) { System.out.println("constructor = " + constructor); } constructors = c.getDeclaredConstructors(); for (Constructor constructor : constructors) { System.out.println("constructor = " + constructor); } Constructor constructor = c.getConstructor(String.class, int.class); System.out.println("constructor = " + constructor); } }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class ReflectUse { public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class c = Person.class;
Constructor constructorA = c.getDeclaredConstructor(null); Constructor constructorB = c.getDeclaredConstructor(String.class, int.class);
Person person = (Person) constructorA.newInstance(null); System.out.println("person = " + person); Person personB = (Person) constructorB.newInstance("Edlison", 18); System.out.println("personB = " + personB);
Method setName = c.getMethod("setName", String.class);
setName.invoke(personB, "edlison"); System.out.println("personB = " + personB);
Field age = c.getDeclaredField("age"); age.setAccessible(true); age.set(personB, 10); System.out.println("personB = " + personB); } }
|
注意:
- 通过
invoke
执行获得的类的方法:(需要执行的对象,形参…)
- 通过
set
对类的属性进行赋值:(需要赋值的对象,形参)
- 如果属性或方法的可见性为
private
,可以通过设置setAccessible(true)
来访问。