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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class ReflectionDemo { private int myInt; private String myString; public ReflectionDemo() { this.myInt = 0; this.myString = "zzz"; } public ReflectionDemo(int myInt, String myString) { this.myInt = myInt; this.myString = myString; } public void printMyInt() { System.out.println(myInt); } public boolean isMyString(String s) { return myString.equals(s); } @Override public String toString() { return "[" + myInt + ", " + myString + "]"; } public static void main(String[] args) throws ReflectiveOperationException {
Class demoClass = Class.forName("ReflectionDemo"); ReflectionDemo demo1 = (ReflectionDemo) demoClass.newInstance(); System.out.println(demo1); Constructor ctor = demoClass.getDeclaredConstructor(int.class, String.class); ReflectionDemo demo2 = (ReflectionDemo) ctor.newInstance(666, "hahaha"); System.out.println(demo2); Field field = demoClass.getDeclaredField("myInt"); field.setAccessible(true); field.set(demo1, 999); Method method1 = demoClass.getDeclaredMethod("printMyInt"); method1.invoke(demo1); method1.invoke(demo2); Method method2 = demoClass.getDeclaredMethod("isMyString", String.class); System.out.println(method2.invoke(demo1, "hahaha")); System.out.println(method2.invoke(demo2, "hahaha")); } }
|