反射

来源:互联网 发布:2017年二级c语言题库 编辑:程序博客网 时间:2024/06/05 17:12

反射机制指的是程序在运行时能够获取自身的信息。在java中,只要给定类的名字,那么就可以通过反射机制来获得类的所有信息


反射构造函数:public Person()

public void test1() throws Exception {Class clazz1 = Class.forName("day01.Person");Constructor c = clazz1.getConstructor(null);Person p = (Person) c.newInstance(null);}

反射构造函数:public Person(String name)

public void test2() throws Exception {Class clazz1 = Class.forName("day01.Person");Constructor c = clazz1.getConstructor(String.class);Person p = (Person) c.newInstance("aaa");}

反射构造函数:public Person(String name,int passwrod)

public void test3() throws Exception {Class clazz1 = Class.forName("day01.Person");Constructor c = clazz1.getConstructor(String.class, int.class);Person p = (Person) c.newInstance("aaa", 3);}

反射构造函数:private Person(List list)

public void test4() throws Exception {Class clazz1 = Class.forName("day01.Person");Constructor c = clazz1.getDeclaredConstructor(List.class);c.setAccessible(true); // 让私有可以访问Person p = (Person) c.newInstance(new ArrayList());}

反射类的方法:public void fun()

public void test5() throws Exception {Class clazz = Class.forName("day01.Person");Person p = (Person) clazz.getConstructor(null).newInstance(null);Method method = clazz.getMethod("fun", null);method.invoke(p, null);}

反射类的方法:public void fun(String name,int password)

public void test6() throws Exception {Class clazz = Class.forName("day01.Person");Person p = (Person) clazz.getConstructor(null).newInstance(null);Method method = clazz.getMethod("fun", String.class, int.class);method.invoke(p, "aa", 123);}

反射类的方法:private void fun(InputStream in)

public void test7() throws Exception {Class clazz = Class.forName("day01.Person");Person p = (Person) clazz.getConstructor(null).newInstance(null);Method method = clazz.getDeclaredMethod("fun", InputStream.class);method.setAccessible(true);method.invoke(p, new FileInputStream("E:\\java\\demo\\Demo1.txt"));}

反射类的方法:public static void fun(int num)

public void test8() throws Exception {Class clazz = Class.forName("day01.Person");Method method = clazz.getMethod("fun", int.class);method.invoke(null, 123);}

反射类的方法:public static void main(String[] args)

public void test9() throws Exception {Class clazz = Class.forName("day01.Person");Method method = clazz.getMethod("main", String[].class);method.invoke(null, (Object) new String[] { "aa", "bb" });}

反射字段 public String name

public void test10() throws Exception {Person p = new Person();Class clazz = Class.forName("day01.Person");Field f = clazz.getField("name");// Person p = (Person) clazz.getConstructor(null).newInstance(null);// 获取字段的值Object obj = f.get(p);// 获取字段类型Class type = f.getType();System.out.println(obj);}

反射字段 privat int passwrod

public void test11() throws Exception {Person p = new Person();Class clazz = Class.forName("day01.Person");Field f = clazz.getDeclaredField("password");f.setAccessible(true);System.out.println(f.get(p));}

反射字段 privat int passwrod

public void test12() throws Exception {Class clazz = Class.forName("day01.Person");Field f = clazz.getDeclaredField("age");f.setAccessible(true);System.out.println(f.get(null));}



Java动态加载类的意义和目的:

Java动态加载类主要是为了不改变主程序代码,通过修改配置文件就可以操作不同的对象执行不同的功能。主要有利于系统的扩展,例如当我要改变一个功能,只需要做一个类,然后编写相应的功能,通过配置文件就可以使用新的功能,不需要修改系统的任何地方,只需要添加一个类;充分实现了松散耦合。

public static void main(String[] args) throws Exception{//完整的路径不是硬编码,而是运算出来的。//InputStream ips = new FileInputStream("config.properties");//InputStream ips = ReflecTest2.class.getClassLoader().getResourceAsStream("hht_xiaohe/Demo1/config.properties");InputStream ips = ReflecTest2.class.getResourceAsStream("config.properties");Properties props = new Properties();props.load(ips);ips.close();String className = props.getProperty("className");//config.properties配置文件中 className=java.util.ArrayList. 所以创建出一个ArrayList集合Collection collections = (Collection) Class.forName(className).newInstance();int x = 1;int y = 2;int z = 3;collections.add(x);collections.add(y);collections.add(z);System.out.println(collections.size());}

动态类Proxy

public static void main(String[] args) throws Exception {//Proxy类的getProxyClass在内存中造出一个字节码(类),在构造时需要告诉他实现了哪些接口Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);//实现Collection接口System.out.println(clazzProxy1.getName());System.out.println("-------begin constructors list------");/* * $Proxy() * $Proxy0(InvocationgHandler,int) */Method[] methods = clazzProxy1.getMethods();for(Method method : methods){String name = method.getName();StringBuilder sBuilder = new StringBuilder(name);sBuilder.append('(');Class[] clazzParams = method.getParameterTypes();for(Class clazzParam : clazzParams){sBuilder.append(clazzParam.getName()).append(',');}if(clazzParams!=null && clazzParams.length == 0)sBuilder.deleteCharAt(sBuilder.length()-1);sBuilder.append(')');System.out.println(sBuilder.toString());}System.out.println("-------begin constructors list------");//Object obj = clazzProxy1.newInstance();Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);//创建Collection对象 方式1class MyInvocationHander1 implements InvocationHandler{@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stubreturn null;}}Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHander1());System.out.println(proxy1.toString());//创建Collection对象 方式2Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stubreturn null;}});//创建Collection对象 方式3Collection proxy = (Collection)getProxy();}public static Object getProxy() {Collection proxy3 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(), new Class[]{Collection.class}, new InvocationHandler(){@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stubArrayList target = new ArrayList();Object retVal = method.invoke(target, args);return retVal;}});return proxy3;}

参考http://blog.csdn.net/chiuan/article/details/7022508



0 0