Home >Java >javaTutorial >Java Tutorial--Basic Strengthening_Reflection

Java Tutorial--Basic Strengthening_Reflection

巴扎黑
巴扎黑Original
2017-06-27 09:19:331474browse

JavaBean: Correspondence between database tables and entity classes
1. If there is a table in the database, there will be a class corresponding to the table
Database: Person table Java: Preson class
2. Table Each column in the table corresponds to a field (member variable) in Java
3. Each row in the table corresponds to an object in Java
Zhang San 18 Male new Person(Zhang San 18 Male);
小花18女 new Person(小花18女);
Multiple objects can be placed in a collection ArrayList

JavaBean contains:
1. Private member variables
2. Public getter/setter method
3. Empty parameter construction method
4.toString method
5. Implement serialization interface

Three ways to obtain class file objects:
1. Use the method getClass() in the Object class
Class getClass() returns the runtime class of this Object.
2. Use class name.class attribute
For each data type, basic data type and reference data type, Java will set a class attribute for it
Class clazz = int.class
Class clazz = String.class
Class clazz = Person.class
3. Use the static method forName
in the Class class static Class forName(String className)
Return with the given string The Class object associated with the named class or interface.

Note: The class file object of each class will only be generated once and is unique

Use reflection technology to obtain the constructor in the class and instantiate it
* public Person() { }
* public Person(String name, int age, String sex) {}
* private Person(String name, int age) {}
*
* Implementation steps:
* 1 .Get the class file object of the Person class
* 2. Use the method getConstructor in the class file object to obtain the constructor method
* 3. Use the method newInstrance in the Constructor to instantiate the constructor method


A quick way to create an empty parameter object using reflection
* Prerequisites for use:
* 1. There must be a constructor with empty parameters in the class
* 2. The modifier of the constructor with empty parameters cannot be private. It is recommended to use public
*
* There is a method in the Class class
* T newInstance() to create a new instance of the class represented by this Class object.
*

Use reflection technology to obtain member variables (fields) in the class, assign values ​​to member variables, and obtain values
* private String name;
* private int age;
* public String sex;
*
* Implementation steps:
* 1. Obtain the class file object of the Person class
* 2. Use the method getField in the class file object to obtain the member variables
* 3 .Use the get/set method in Field to obtain the member variable value, and assign the value to the member variable

 1  public static void main(String[] args) throws Exception { 2         //1.获取Person类的class文件对象 3         Class clazz = Class.forName("cn.itcast.demo02.javabean.Person"); 4         //2.使用class文件对象中的方法getField获取成员变量 5         /* 6          *  Field[] getFields()  获取类中所有可访问公共字段。 7          *  Field[] getDeclaredFields()  获取类中所有的声明字段,包含私有的。 8          */ 9         Field[] fields1 = clazz.getFields();10         for (Field field : fields1) {11             System.out.println(field);12         }13         System.out.println("------------------");14         Field[] fields2 = clazz.getDeclaredFields();15         for (Field field : fields2) {16             System.out.println(field);17         }18         System.out.println("------------------");19         20         /*21          * Field getField(String name)  获取类中指定公共成员字段。22          * Field getDeclaredField(String name)  获取类中指定的声明字段,包含私有的。23          * 参数:24          *     String name:字段的名字25          */26         //public String sex;27         Field sexField = clazz.getField("sex");28         System.out.println(sexField);29         //private String name;30         Field nameField = clazz.getDeclaredField("name");31         System.out.println(nameField);32         //private int age;33         Field ageField = clazz.getDeclaredField("age");34         System.out.println(ageField);35         36         /*37          * 3.使用Field中的方法get/set获取成员变量值,给成员变量赋值38          * Object get(Object obj) 返回指定对象上此 Field 表示的字段的值。 
39          * void set(Object obj, Object value) 将指定对象变量上此 Field 对象表示的字段设置为指定的新值。40          * 参数:41          *     Object obj:要设置值/获取的值的对象,可以使用反射快速创建42          *     Object value:给成员变量设置的实际值43          * 返回值:44          *     Object:获取成员变量的返回值    
45          */46         //使用反射创建对象47         Object obj = clazz.newInstance();48         49         //public String sex;50         //get(obj);-->getSex();51         Object sexValue = sexField.get(obj);52         System.out.println(sexValue);//默认值 null53         54         /*55          * private String name;56          * 私有的属性无法直接使用,必须先取消Java的权限检查(暴力反射)57          */58         nameField.setAccessible(true);59         Object nameValue = nameField.get(obj);60         System.out.println(nameValue);//默认值 null61         62         //private int age;63         ageField.setAccessible(true);64         Object ageValue = ageField.get(obj);65         System.out.println(ageValue);//默认值 066         System.out.println("------------------");67         /*68          * 设置成员变量的值69          */70         //public String sex;71         sexField.set(obj, "妖");72         //获取值73         sexValue = sexField.get(obj);74         System.out.println(sexValue);//妖75         76         //private String name;77         nameField.set(obj, "泰国美女");78         //获取值79         nameValue = nameField.get(obj);80         System.out.println(nameValue);//泰国美女81         82         //private int age;83         ageField.set(obj, 18);84         //获取值85         ageValue = ageField.get(obj);86         System.out.println(ageValue);//1887         System.out.println(obj);//Person [name=泰国美女, age=18, sex=妖]88     }

Use reflection technology to obtain the member method in the class, and execute
* public String getName ()
* public void setName(String name)
* private void method()
*
* Implementation steps:
* 1. Get the class file object of the Person class
* 2. Use the method getMethod in the class file object to obtain the member method
* 3. Use the method invoke in the Method to execute the obtained method
*
* Method in the Method class: getName, get the method name
* String getName() returns the method name represented by this Method object in String form.

 1 public static void main(String[] args) throws Exception { 2         //1.获取Person类的class文件对象 3         Class clazz = Class.forName("cn.itcast.demo02.javabean.Person"); 4         //2.使用class文件对象中的方法getMethod获取成员方法 5         /* 6          * Method[] getMethods() 获取类中所有的公共方法,包含继承父类的 7          * Method[] getDeclaredMethods() 包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。 
 8          */ 9         Method[] methods1 = clazz.getMethods();10         for (Method method : methods1) {11             System.out.println(method);12         }13         System.out.println("----------------------");14         Method[] methods2 = clazz.getDeclaredMethods();15         for (Method method : methods2) {16             System.out.println(method.getName());17         }18         System.out.println("----------------------");19         /*20          *  Method getMethod(String name, Class<?>... parameterTypes) 获取类中指定公共成员方法。21          *  Method getDeclaredMethod(String name, Class<?>... parameterTypes) 获取类中指定的成员方法,包含私有的.22          *  参数:23          *      String name:方法的字符串名称24          *      Class<?>... parameterTypes:方法参数列表的class对象    
25          */26         //public String getName()27         Method getNameMethod = clazz.getMethod("getName");28         System.out.println(getNameMethod);29         30         //public void setName(String name)31         Method setNameMethod = clazz.getMethod("setName", String.class);32         System.out.println(setNameMethod);33         34         //private void method()35         Method privateMethod = clazz.getDeclaredMethod("method");36         System.out.println(privateMethod);37         38         /*39          * 3.使用Method中的方法invoke执行获取到的方法40          * Object invoke(Object obj, Object... args) 
41          * 参数:42          *     Object obj:要执行的方法的所属对象43          *     Object... args:执行方法,传递的实际参数44          * 返回值:45          *     Object:方法的返回值46          *     如果方法没有返回值,Object的值为null47          */48         Object obj = clazz.newInstance();49         50         //public String getName()51         Object v1 = getNameMethod.invoke(obj);52         System.out.println(v1);//成员变量 name的默认值:null53         54         //public void setName(String name)55         Object v2 = setNameMethod.invoke(obj, "楼上老宋");56         System.out.println(v2);57         58         v1 = getNameMethod.invoke(obj);59         System.out.println(v1);//成员变量 name的值:楼上老宋60         61         /*62          * private void method()63          * 使用暴力反射,取消Java的权限检查64          */65         privateMethod.setAccessible(true);66         privateMethod.invoke(obj);//私有方法67         68         System.out.println("-------------");69         //获取返回值为数组的方法70         Method arrMethod = clazz.getMethod("methodArr");71         Object v3 = arrMethod.invoke(obj);72         int[] arr = (int[]) v3;73         System.out.println(v3);74         System.out.println(arr);75         for (int i : arr) {76             System.out.println(i);77         }78     }

Comprehensive case of reflection:
* Obtain JavaBean objects through reflection technology, and inject (assign) values ​​to JavaBean member variables
*
* Implementation Steps:
* 1. Create a JavaBean (User class)
* 2. Create a data.properties configuration file and configure the actual values ​​of member variables
* 3. Use the IO+Properties collection to read the configuration file, and save the data in the file to the collection
* 4. Use reflection technology to create a JavaBean object
* 5. Traverse the Properties collection
* 6. Use the Properties collection key to splice the setXXX method
* 7 .Use reflection technology to obtain the setXXX method
* 8.Use reflection technology to execute the setXXX method and inject values ​​into member variables

 1 public static void main(String[] args) throws Exception { 2         //3.使用IO+Properties集合,读取配置文件,把文件中的数据保存到集合中 3         Properties prop = new Properties(); 4         prop.load(new FileReader("data.properties")); 5         //4.使用反射技术创建JavaBean对象 6         Class clazz = Class.forName("cn.itcast.demo02.javabean.User"); 7         Object obj = clazz.newInstance(); 8         //5.遍历Properties集合 9         Set<String> set = prop.stringPropertyNames();10         for (String key : set) {11             /*12              * 6.使用Properties集合key拼接setXXX方法13              * 类中的set方法:14              *     setId,setUsername,setPassword15              * 集合的key:16              *     id,username,password17              * 拼接的过程:18              *     1.固定的字符串:"set"19              *     2.获取key的首字母,变成大写20              *     3.获取key的其它字母21              */22             String methodName = "set"+key.substring(0, 1).toUpperCase()+key.substring(1);23             //System.out.println(methodName);24             25             //7.使用反射技术获取setXXX方法26             Method setMethod = clazz.getMethod(methodName, String.class);27             //8.使用反射技术执行setXXX方法,给成员变量注入值(集合的value值)28             setMethod.invoke(obj, prop.get(key));29             30             /*31              * 扩展:拼接getXXX方法32              */33             String getMethodName = "get"+key.substring(0, 1).toUpperCase()+key.substring(1);34             Method getMethod = clazz.getMethod(getMethodName);35             Object value = getMethod.invoke(obj);36             System.out.println(value);37         }38         System.out.println(obj);39     }

Use reflection technology to obtain the interface
* Class[] getInterfaces() determines the interface implemented by the class or interface represented by this object

 1  public static void main(String[] args) throws Exception { 2         //获取接口实现类的class文件对象 3         Class clazz = Class.forName("cn.itcast.demo06.reflect.AandBImpl"); 4         //使用Class中的方法getInterfaces获取实现的实现的接口 5         Class[] clazzs = clazz.getInterfaces(); 6         for (Class c : clazzs) { 7             System.out.println(c);//接口 8             //使用接口class文件对象,创建实现类对象,调用实现类中的方法 9             Object obj = clazz.newInstance();10             Method method = c.getMethod("a");11             method.invoke(obj);12         }13     }

The above is the detailed content of Java Tutorial--Basic Strengthening_Reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn