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
| package com.sympa.lesson01;
import java.lang.reflect.Constructor; 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, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
Class clazz = Person.class; Constructor cons = clazz.getConstructor(String.class, int.class); Object obj = cons.newInstance("Tom", 12); Person p = (Person) obj; System.out.println(p.toString());
Field age = clazz.getField("age"); age.set(p, 10); System.out.println(p.toString());
Method show = clazz.getDeclaredMethod("show"); show.invoke(p); } }
class Person { private String name; public int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public void show() { System.out.println(name + age); } }
|