Java Class object reflected in acquisition mode

1. What is the reflection

Reflector: is the reverse processing target .
So what positive action is? When we instantiate an object, first create a class, new one of its constructor can instantiate an object. It is a process flow: . Package name class name ; by the package name, find the class name.
Reflected in the "reverse": is based on the object to obtain sources of information objects . And this anti operation depends on a core method of Object. Get Class object.

public final native Class<?> getClass();

This method returns a Class class object, the Class class is described .
In reflection of the world where fancy is not an object, but the object behind the composition class (the class, structure, ordinary members).

Three kinds of class 2. Class object acquisition mode

Type (class) of an abstract, the JDK is Class class, the class used to describe our definition.
Class of Access:

  1. By the object getClassacquisition method, for example: obj.getClass ();
  2. By 类名.classobtaining the object class;
  3. By static method of class Class forName(String className)Gets the Class object you want to catch the exception.

In the above three methods, we can see that, in addition to instantiate an object class is generated first method, the other two will not be generated class instance object. Therefore, an object of class Class achieved a most direct benefits: by reflection instantiate the object.
Example: three ways of acquiring object information Class


public class TestReflect {
    public static void main(String[] args) {
        //1.第一种方式
        //通过类名,调用构造方法,创建对象
        Date date = new Date();
        //通过date对象来获取创建date的类型,赋给Class对象
        Class classz = date.getClass();

        System.out.println(classz);   //class java.util.Date
        System.out.println(classz.getName());  //java.util.Date

        //第二种方式
        //不需要实例化对象,   类名.class
        Class classz1 = Date.class;
        System.out.println(classz1 == classz);  //true

        //第三种方式
        //使用Class的静态方法,其中forName中的类名称是所在的包名加类名
        try {
            Class classz2 = Class.forName("java.util.Date");
            System.out.println(classz2 == classz1);  //true
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

So how by reflecting object instance , Class provided a method. as follows:

public T newInstance()
        throws InstantiationException, IllegalAccessException

That is, when we get information object class, the Class object by calling newInstance()the method ( equivalent to a new object ), instantiate an object.
Example: instantiating the object by reflection


public class TestReflect {
    public static void main(String[] args) {
        //第二种方式
        Class classz = Date.class;
        try {
            //此处就等价于new java.util.Date
            Object object = classz.newInstance();
            System.out.println(object);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println();

        //第三种方式
        try {
            Class classz1 = Class.forName("java.util.Date");
            Object object = classz1.newInstance();
            System.out.println(object);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}

Now we find instantiate an object of the second approach: reflection achieved .
Class object made longer means the right to operate a specified class.

3. Application of reflection

Application of simple factory pattern

For a conventional plant (Simple plant), when adding a new class of products, to modify the code of the factory process, contrary to the shutter principle .
For example as follows:


interface Fruit{
    void eat();
}

class Apple implements Fruit{
    @Override
    public void eat() {
        System.out.println("吃苹果");
    }
}

class FruitFactory{
    public static Fruit getFruitInstance(String fruitName){
        if(fruitName.equals("Apple")){
            return new Apple();
        }
        return null;
    }
}
public class TestFactory {
    public static void main(String[] args) {
        Fruit fruit = FruitFactory.getFruitInstance("Apple");
        fruit.eat();
    }

}

If you want to add at this time a product like orange, then it would have to modify the code in the factory class . So can be solved by reflection, since the reflection can instantiate an object Class object to the newInstance () .
Example: use simple factory method after reflection


interface Fruit{
    void eat();
}

class Apple implements Fruit{
    @Override
    public void eat() {
        System.out.println("吃苹果");
    }
}

class FruitFactory{
    public static Fruit getFruitInstance(String className){
        try {
            Class classz = Class.forName(className);
            return (Fruit) classz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public class TestFactory {
    public static void main(String[] args) {
        Fruit fruit = FruitFactory.getFruitInstance("www.csdn.classse.Apple");
        fruit.eat();
    }

}

Simple plant used in conjunction with reflection can be reduced to modify the function expansion problems caused by, when adding a new interface subclass can easily subcategory expansion interface .

Guess you like

Origin blog.csdn.net/mi_zhi_lu/article/details/91450670