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
| package com.sympa.lesson01;
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
public class ReflectionTest {
public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<Person> clazz = Person.class; Person person = clazz.getDeclaredConstructor().newInstance(); Field age = clazz.getDeclaredField("age"); age.set(person, 10); int ans = (int)age.get(person); System.out.println(ans);
Method show = clazz.getDeclaredMethod("show", int.class); show.setAccessible(true); show.invoke(person, 2); } }
|