首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java反射实践小结

2013-12-28 
Java反射实践总结import java.lang.reflect.Constructorimport java.lang.reflect.Fieldimport java.lan

Java反射实践总结

import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class TestReflect {public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, NoSuchFieldException {//1.1 默认构造函数Constructor<Test> tConstructor = (Constructor<Test>) Class.forName("Test").getConstructor();Test test = tConstructor.newInstance(new Object[]{});//1.2 带参数构造函数Constructor<Test> tConstructor2 = (Constructor<Test>) Class.forName("Test").getConstructor(int.class);Test test2 = tConstructor2.newInstance(new Object[]{200});//2.1 普通无参数成员函数Method method1 = Class.forName("Test").getMethod("sayHello");method1.invoke(test);//2.2 带普通参数成员函数Method method2 = Class.forName("Test").getMethod("run",String.class);method2.invoke(test2, "haha");//2.3 参数为数组的成员函数Method method3 = Class.forName("Test").getMethod("printArray", String[].class);//method3.invoke(test2, new String[]{"i","am","hello world"})这样子数组会被打开,认为是有四个参数;method3.invoke(test2, new Object[]{new String[]{"i","am","hello world"}});//3.静态函数Method method4 = Class.forName("Test").getMethod("service");method4.invoke(null);//4 普通成员Field afield = Test.class.getDeclaredField("a");afield.setAccessible(true);afield.set(test, 99999);Field bField = Test.class.getDeclaredField("str");bField.setAccessible(true);bField.set(test, "i am a  field");System.out.println(test);//5 静态成员Field cfield = Test.class.getDeclaredField("c");cfield.setAccessible(true);cfield.set(null, 11111);Test.printStatic();}}//目标类class Test {private int a;private String str;private static int  c;public Test(int a) {System.out.println("a: "+a);}public Test() {System.out.println("default constructor");}public void sayHello(){System.out.println("hello world");}public int run(String arg) {System.out.println("run: "+arg);return 0;}public void printArray(String[] array) {for(String str:array){System.out.print(str+" ");}System.out.println();}@Overridepublic String toString() {return "a: "+a+" str: "+str;}public static void service() { System.out.println("I am service function");}public static void printStatic() {System.out.println("c: "+c);}}

热点排行