[关闭]
@snail-lb 2017-02-28T23:22:47.000000Z 字数 6409 阅读 934

java反射

java进阶


java反射学习

本文采用例子进行学习,直接看示例程序应该就能看懂。

一、反射的基本操作

用于操作的Student类

  1. package com.cn.reflect;
  2. public class Student {
  3. private String name;
  4. private int age;
  5. public Student() {
  6. }
  7. public Student(String name,int age) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. public int getAge() {
  12. return age;
  13. }
  14. public void setAge(int age) {
  15. this.age = age;
  16. }
  17. public void display() {
  18. System.out.println("学生信息: name=" + name + " age=" + age);
  19. }
  20. public void say(String str){
  21. System.out.println("学生说:" + str);
  22. }
  23. }

使用的反射对学生类进行操作

  1. package com.cn.reflect;
  2. import java.lang.reflect.Constructor;
  3. import java.lang.reflect.Field;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6. import java.lang.reflect.Modifier;
  7. /**
  8. * java反射
  9. *
  10. * @author lvbiao
  11. *
  12. */
  13. public class TestReflect {
  14. public static void main(String[] args) {
  15. Class test = null;
  16. try {
  17. test = Class.forName("com.cn.reflect.Student");
  18. } catch (ClassNotFoundException e) {
  19. e.printStackTrace();
  20. }
  21. //获取完整类名
  22. System.out.println("------获取完整类名----------");
  23. System.out.println("完整类名:" + getMothodName(test));
  24. //无参构造实例化对象
  25. System.out.println("------无参构造实例化对象----------");
  26. Student stu1 = (Student) getObjectNoParameters(test);
  27. stu1.display();
  28. //通过其他构造函数实例化对象
  29. System.out.println("------通过其他构造函数实例化对象-----");
  30. Student stu2 = (Student) getObjectHaveParameters(test);
  31. stu2.display();
  32. //获取类全部属性信息
  33. System.out.println("------获取类全部属性信息----------");
  34. AttributeInfo(test);
  35. //获取全部方法信息
  36. System.out.println("------获取全部方法信息-----------");
  37. MethodInfo(test);
  38. //调用类中无参方法
  39. System.out.println("------调用类中无参方法-----------");
  40. callMethodNoParameters(test,"display");
  41. //调用类中有参方法
  42. System.out.println("------调用类中有参方法-----------");
  43. callMethodHaveParameters(test,"say","hello");
  44. //通过反射来操作属性
  45. System.out.println("------通过反射来操作属性,设置名字为Bob-----------");
  46. setAttribute(test,"name","Bob");
  47. }
  48. // 获取完整类名
  49. public static String getMothodName(Class cla) {
  50. return cla.getName();
  51. }
  52. // 通过无参构造 实例化对象
  53. public static Object getObjectNoParameters(Class cla) {
  54. try {
  55. return cla.newInstance();
  56. } catch (InstantiationException e) {
  57. e.printStackTrace();
  58. } catch (IllegalAccessException e) {
  59. e.printStackTrace();
  60. }
  61. return null;
  62. }
  63. // 通过有参构造 实例化对象
  64. public static Object getObjectHaveParameters(Class cla) {
  65. Constructor<?> cons[] = cla.getConstructors();
  66. Object obj = null;
  67. try {
  68. obj = cons[1].newInstance("张三",23);
  69. } catch (InstantiationException e) {
  70. e.printStackTrace();
  71. } catch (IllegalAccessException e) {
  72. e.printStackTrace();
  73. } catch (IllegalArgumentException e) {
  74. e.printStackTrace();
  75. } catch (InvocationTargetException e) {
  76. e.printStackTrace();
  77. }
  78. return obj;
  79. }
  80. //获取类全部属性信息
  81. public static void AttributeInfo(Class cla){
  82. Field[] field = cla.getDeclaredFields();
  83. for (int i = 0; i < field.length; i++) {
  84. // 权限修饰符
  85. int mo = field[i].getModifiers();
  86. String priv = Modifier.toString(mo);
  87. // 属性类型
  88. Class<?> type = field[i].getType();
  89. System.out.println(priv + " " + type.getName() + " "
  90. + field[i].getName() + ";");
  91. }
  92. }
  93. //获取类中方法
  94. public static void MethodInfo(Class cla){
  95. Method[] method = cla.getDeclaredMethods();
  96. for (int i = 0; i < method.length; i++) {
  97. // 权限修饰符
  98. int mo = method[i].getModifiers();
  99. String priv = Modifier.toString(mo);
  100. //获取返回类型
  101. String retu = method[i].getReturnType().getName();
  102. // 属性类型
  103. String name = method[i].getName();
  104. System.out.println(priv + " " + retu + " "
  105. + name + "()");
  106. }
  107. }
  108. //调用无参方法
  109. public static void callMethodNoParameters(Class cla,String methodName){
  110. try {
  111. Method method1 = cla.getMethod(methodName);
  112. method1.invoke(cla.newInstance());
  113. } catch (NoSuchMethodException e) {
  114. e.printStackTrace();
  115. } catch (SecurityException e) {
  116. e.printStackTrace();
  117. } catch (IllegalAccessException e) {
  118. e.printStackTrace();
  119. } catch (IllegalArgumentException e) {
  120. e.printStackTrace();
  121. } catch (InvocationTargetException e) {
  122. e.printStackTrace();
  123. } catch (InstantiationException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. //调用有参方法
  128. public static void callMethodHaveParameters(Class cla,String methodName,String parameter){
  129. try {
  130. Method method2=cla.getMethod(methodName, String.class);
  131. method2.invoke(cla.newInstance(),parameter);
  132. } catch (NoSuchMethodException e) {
  133. e.printStackTrace();
  134. } catch (SecurityException e) {
  135. e.printStackTrace();
  136. } catch (IllegalAccessException e) {
  137. e.printStackTrace();
  138. } catch (IllegalArgumentException e) {
  139. e.printStackTrace();
  140. } catch (InvocationTargetException e) {
  141. e.printStackTrace();
  142. } catch (InstantiationException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. //通过反射来操作属性
  147. public static void setAttribute(Class cla,String key,String value){
  148. try {
  149. Object obj = cla.newInstance();
  150. Field field = cla.getDeclaredField(key);
  151. field.setAccessible(true);
  152. field.set(obj,value);
  153. //调用方法来验证是否设置成功
  154. Method method = cla.getMethod("display");
  155. method.invoke(obj);
  156. } catch (InstantiationException e) {
  157. e.printStackTrace();
  158. } catch (IllegalAccessException e) {
  159. e.printStackTrace();
  160. } catch (NoSuchFieldException e) {
  161. e.printStackTrace();
  162. } catch (SecurityException e) {
  163. e.printStackTrace();
  164. } catch (NoSuchMethodException e) {
  165. e.printStackTrace();
  166. } catch (IllegalArgumentException e) {
  167. e.printStackTrace();
  168. } catch (InvocationTargetException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. }

二、 利用反射实现的代理模式

动态代理的项目接口

  1. package com.cn.reflect.DynamicProxy;
  2. public interface Subject {
  3. public void say(String name,int age);
  4. }

项目实现

  1. package com.cn.reflect.DynamicProxy;
  2. public class RealSubject implements Subject{
  3. @Override
  4. public void say(String name, int age) {
  5. System.out.println(name + "今年已经" + age + "岁了。");
  6. }
  7. }

代理实现类

  1. package com.cn.reflect.DynamicProxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. public class MyInvocationHandler implements InvocationHandler {
  6. private Object obj = null;
  7. public Object bind(Object obj) {
  8. this.obj = obj;
  9. return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
  10. }
  11. @Override
  12. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  13. Object temp = method.invoke(this.obj, args);
  14. return temp;
  15. }
  16. }

测试类

  1. package com.cn.reflect.DynamicProxy;
  2. public class Test {
  3. public static void main(String[] args) {
  4. MyInvocationHandler demo = new MyInvocationHandler();
  5. Subject sub = (Subject) demo.bind(new RealSubject());
  6. sub.say("Rollen",23);
  7. }
  8. }

三、使用反射完成的工厂模式

1.公共接口

  1. package com.cn.reflect.FactoryPattern;
  2. public interface Fruit {
  3. public abstract void eat();
  4. }

2.实现类一

  1. package com.cn.reflect.FactoryPattern;
  2. public class Apple implements Fruit {
  3. @Override
  4. public void eat() {
  5. System.out.println("吃苹果");
  6. }
  7. }

3.实现类二

  1. package com.cn.reflect.FactoryPattern;
  2. public class Orange implements Fruit{
  3. @Override
  4. public void eat() {
  5. System.out.println("吃橘子");
  6. }
  7. }

4.工厂方法

  1. package com.cn.reflect.FactoryPattern;
  2. public class FruitFactory {
  3. public static Fruit getInstance(String ClassName){
  4. Fruit fruit = null;
  5. try {
  6. fruit = (Fruit) Class.forName(ClassName).newInstance();
  7. } catch (InstantiationException e) {
  8. e.printStackTrace();
  9. } catch (IllegalAccessException e) {
  10. e.printStackTrace();
  11. } catch (ClassNotFoundException e) {
  12. e.printStackTrace();
  13. }
  14. return fruit;
  15. }
  16. }

5.测试类

  1. package com.cn.reflect.FactoryPattern;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Fruit apple = FruitFactory.getInstance("com.cn.reflect.FactoryPattern.Apple");
  5. apple.eat();
  6. }
  7. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注