Close to 8 thousand words reflecting dry goods | [] advanced java, java reflection succinctly

java reflection mechanism succinctly

Contents
Concepts reflection mechanism
base class 2. Class reflected
3. The use of reflected
Application Example 4. reflected

About the author: full stack study notes, people are working in a
micro-channel public number: No. Public day more wonderful day push Essay
Here Insert Picture Description

The concept of reflection:

In the operating state, for any class, you can obtain all the properties and methods of this type, for any object that can invoke any of its methods and properties (including proprietary methods and properties), which dynamically acquires function information and the method of dynamic invocation object is called a reflection java language. Reflections are seen as key to dynamic languages. Reflection is simply mapped to the various components of the corresponding java class java.

Popular speak, by reflection, the class is completely transparent to us, you want to get anything can be. The method comprises constructing, properties, methods.

java reflection mechanism provides functionality :

Analyzing the runtime class of any one object belongs;
object constructor any class at runtime;
Analyzing member variables and methods any class has at runtime;
calling a specified object's method at runtime;
generate dynamic proxy.

In fact, this is also related to the dynamic and static language, java language itself is not a dynamic language, but he has a very prominent dynamic mechanism, what we call reflection.
What is a dynamic language? That is, when the program is running, (note that it is time to run, not compile time) allows changing the program structure or variable type. Conversely static is no such personality.

Class reflected base class

Class class is the basis of reflection to achieve, so I want to learn to reflection, you must first master the basic concepts of class Class.
What class is? Class class is an instance of an object class, so that the Class class is the class of all classes.

To Anatomy of a class, you must first get to the bytecode file object class. Class is the method used by the anatomy class, the first to obtain the object of each type Class file byte code corresponds.

Class no public constructor class, Class object class is loaded by the time the Java virtual machine and an automatic calling method defineClass configured by the class loader, it is not explicitly declared a Class object. Here also involves a load of things, like

Briefly explain:

Class loader: the time when the program needs to be with a class if the class has not been loaded into memory, the system will by loading the connection, this initialization initialize class three steps

Load: refers to the class file is read into memory (file after the compilation is .class file), and whom to create a Class object
when any class is used, the system will build a Class object, the first time will be the second times will determine the class exists.

Connections: Verify that you have the correct internal structure, and other types of coordinated and
ready to allocate memory for static member of the class, and set the default initialization value
and make a resolution: binary data class character references replaced by a direct reference.

Speaking above the Class object can not be created directly, but we can get the Class class in other ways, there are three ways to get the Class class we want, you can normally use reflection to get a Class after class.

Class three ways of acquiring (obtaining a class bytecode object):

The first: using an object access, use objects get getClass

Person person = new Person();
Class clazz = person.getClass();

The second: use a static class property

Class clazz = Person.class

Third: static method forName Class class (class name string)
Note; write the full name of the class package name

Class clazz = Calss.forName("…….");

Well, the focus here, reflecting how to play it fun!

Usage reflected ##

It says what can be obtained through any of a class of reflection, let's see if it is true.

The first step to doing ? Of course, this can be obtained by the class which pleases Class previous three methods. There are three methods, we first have to be an example of it!
The Code

//获取Class第一种方法
Student student = new Student();
Class clazz = student.getClass();
//获取Class第二种方法
Class clazzTwo = Student.class;
//获取Class第三种方法
Class clazzThree = Class.forName("demo.qzxxbj.entity.Student");

System.out.println("第一个"+clazz+"\n第二个"+clazzTwo+"\n第三个"+clazzThree);

result

第一个class demo.qzxxbj.entity.Student
第二个class demo.qzxxbj.entity.Student
第三个class demo.qzxxbj.entity.Student

Class object you can see three methods are the same, no difference.
The third method is a class not found exception will be thrown.
Student of which is a simple class can be any class.

Get property by any class of Class
codes Student class

package demo.qzxxbj.entity;

/**
 * @author 微信公众号:全栈学习笔记
 * @date 2020/3/29
 * @description
 */

public class Student {
private String name;
private Integer age;
private String sex;
public int number;

public int getNumber() {
    return number;
}

public void setNumber(int number) {
    this.number = number;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String getSex() {
    return sex;
}

public void setSex(String sex) {
    this.sex = sex;
}

}

The following methods are used to obtain Class A second, more concise

	//获取Class第二种方法
    Class clazzTwo = Student.class;

    //获取该类指定属性名的public成员变量,包括父类的
    Field field = clazzTwo.getField("number");

    //field   public int demo.qzxxbj.entity.Student.number
    System.out.println("该类指定属性名的public成员变量,包括父类的"+field);

    //获取该类指定名称声明的变量,即不包括父类的
    Field deField = clazzTwo.getDeclaredField("name");

    // deField  private java.lang.String demo.qzxxbj.entity.Student.name
    System.out.println("该类所有声明的变量,即不包括父类的"+deField);

    //获取该类所有的public声明的成员变量
    Field fields[] = clazzTwo.getFields();

    System.out.println("public声明的变量:");
    //public int demo.qzxxbj.entity.Student.number
    for (Field field1:fields){
        System.out.println(field1);
    }

    //获取该对象的所有成员变量
    Field deFields[] = clazzTwo.getDeclaredFields();
    System.out.println("该对象的所有成员变量");
    //private java.lang.String demo.qzxxbj.entity.Student.name
    //private java.lang.Integer demo.qzxxbj.entity.Student.age
    //private java.lang.String demo.qzxxbj.entity.Student.sex
    //public int demo.qzxxbj.entity.Student.number
    for (Field field1:deFields){
        System.out.println(field1);
    }

Remember getFields (), getField (String name), getDeclaredFields (), the difference getDeclaredField (String name), you will be able to take this knowledge to grasp the point!

Acquisition by any member of the Class method

Or to see the code!

Acquiring member method Method

	//获取Class第二种方法
    Class clazzTwo = Student.class;
    //根据方法名以及参数类型获取,只能获取public声明的方法,包括父类的
    Method method = clazzTwo.getMethod("setAge",Integer.class);

    //public java.lang.Integer demo.qzxxbj.entity.Student.getAge()
    System.out.println(method);

    //根据方法名以及参数名称获取该类声明的所有的属性方法,不包括父类的
    Method deMethod = clazzTwo.getDeclaredMethod("setAge", Integer.class);

    System.out.println(deMethod);

    //获取该对象声明的所有的public方法,包括父类的
    Method methods[] = clazzTwo.getMethods();

    //获取该对象声明的所有的方法,但是不包含父类的方法
    Method deMethods[] = clazzTwo.getDeclaredMethods();

What a way to print out the Method is it? The above code is also included

public void demo.qzxxbj.entity.Student.setAge(java.lang.Integer)

And speak before Field is not very similar.
Now comes the method, then it certainly involves a method call , we get these methods, how should I call this class which way to do that? Use the invoke function, Method class which contains invoke a function, good to know English, this invoke of the Chinese means "to call."
How to use it?

    //获取Class第二种方法
    Class clazzTwo = Student.class;
    //根据方法名以及参数类型获取,只能获取public声明的方法,包括父类的
    Method method = clazzTwo.getMethod("setAge",Integer.class);

    //public java.lang.Integer demo.qzxxbj.entity.Student.getAge()
    System.out.println(method);

    //利用Class创建一个对象的实例
    Student student = (Student) clazzTwo.newInstance();

    //函数调用
    Object value = method.invoke(student,20);
    //null
    System.out.println(value);

The code above, you may not understand, I am speaking about, first of all, we get a Class class, and then we get this kind of a method by setAge this Class, continued to call this method after obtaining this method, call the method is not it should be called an instance of an object inside the method? So we need to instantiate an object, by what methods it, (), create an instance of class through the inside of the newInstance, this method requires the instance of the class has a constructor without parameters. There are other methods to create an instance, we would say later. After you create an instance of an object, we can begin to call the method.
By invoke method call, invoke the first parameter is an instance of an object, or I go looking for this method. The second argument, or a third, and so on, which all parameters are behind me call has parameters, according to go in order to fill OK. Then the function returns an Object object, you can think of, I call a method is not to make him do something, to do these things need to return a thing, I do not know what this thing is, to use Object Gets thing. Because we're calling this method does not require the return value, so that the null. It is not simple.

Get Class constructor by

This is me on the last to learn, after all, I think the use of relatively small proportion. Together to learn about how to obtain construction method with Class, and call him.

public Student(String name, int id) {
    this.name = name;
    this.id = id;
}

Here we are in the Student class which adds a constructor.

Then we get to the constructor.

	//获取Class第二种方法
    Class clazzTwo = Student.class;

    //获取无参构造方法,public声明的,包括父类,加上参数时就是获取特定的构造方法
    Constructor constructor = clazzTwo.getConstructor();

    //public demo.qzxxbj.entity.Student()
    System.out.println(constructor);

    //获取该类所有的public声明的构造方法
    Constructor constructors[] = clazzTwo.getConstructors();

    //获取指定参数的构造方法
    Constructor deConstructor = clazzTwo.getDeclaredConstructor(String.class,Integer.class);

    //获取所有的该类的构造方法,不包括父类的
    Constructor deConstructors[] =clazzTwo.getDeclaredConstructors();

The code above should be easy to understand, and I will not elaborate. Here to talk about how to use the constructor obtained, by definition is the constructor to instantiate an object, the above we have when it comes to how to instantiate an object through the Class, let's instantiate an object by constructing square method

	Student student = (Student) deConstructor.newInstance("全栈学习笔记",21);

    //21
    System.out.println(student.getAge());

Now know it, we are not poor reflection of the function finished, he sent a reflection of the dynamic proxy, this is more important, a blog will be a special code word is not easy. I want to point followers. Micro-channel public number: full stack study notes, Essay wonderful day push for you.

Finally I wrote a java sql statement stitching reflection of my own previous experience, the equivalent is the application of a reflection of it.

Application Example reflected

By reflection to dynamically generated SQL statement, is not it feel a bit fast hardware?
Directly on the code, and I only made a SQL statement, and interested private letter I find I can get the complete code!

public  String insert(Object object) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {`
    //insert into student(id,name,sex) values (1,"全栈学习笔记","男")
    StringBuilder sql = new StringBuilder();
    Class clazz = object.getClass();
    sql.append("insert into ");

    sql.append(clazz.getSimpleName()+"(");
    Field[] fields = clazz.getDeclaredFields();
    for(Field field:fields){
        sql.append(field.getName()+",");
    }
    sql.deleteCharAt(sql.length()-1);
    sql.append(")");
    sql.append(" values (");
    for(Field field:fields){
        field.setAccessible(true);
       Object value = field.get(object);

       String fieldName = field.getName();
       String str1 = fieldName.substring(0,1).toUpperCase();
       String str2 = fieldName.substring(1,fieldName.length());
       String strValue = str1.concat(str2);
		//String strValue = fieldName.substring(0,1).toUpperCase().concat(fieldName.substring(1,fieldName.length()));
       Method method = clazz.getMethod("get"+strValue,null);

       Object value1 = method.invoke(object,null);

//     if(value1.getClass().equals(String.class))
//     if(field.getType().equals(String.class))
        if(value1 instanceof String){
            sql.append("\"").append(value1).append("\"").append(",");
        }else {
            sql.append(value1).append(",");
        }
    }
    sql.deleteCharAt(sql.length()-1);
    sql.append(")");
    System.out.println(sql.toString());
    return sql.toString();
}

This issue to explain on here, should also back out of an article about the annotations, if you find the article in the wrong place, please point out to Oh! If you think you can learn a lot of knowledge, make a point of concern Oh! Welcome to forward! Make more friends learn!

Released seven original articles · won praise 2 · Views 521

Guess you like

Origin blog.csdn.net/enxiaobai123/article/details/105193822
Recommended