Reflection (on)

table of Contents

reflection

Reflection is one of the most important parts of Java, the use of high reflection code reuse can be achieved.

1, refers to a Java program running analyzing, modifying, and the ability to operate the class object.
2, Class class is the foundation of Java reflection mechanism, we can get through the Class class information about a class.
3, the object of the class Class represent classes and interfaces for the Java application program currently running in. Class class is a Java reflection mechanism inlet.
4, the plurality of classes into one common generic class, thereby improving the reusability of code.

Here Insert Picture Description

Reflection may be obtained by the instance of class Class three forms.

Example:

public class TestReflection {
    public static void main(String[] args) throws ClassNotFoundException {
        Ball ball = new Ball();
        //第一种
        Class<?> ballClassA = ball.getClass();
        //第二种
        Class<?> ballClassB = Ball.class;
        //第三种,在不考虑复杂开发时,用第三种
        Class<?> ballClassC = Class.forName("com.tx.test.reflection.Ball");
        
        System.out.println(ballClassC);
        System.out.println(ballClassC.getName());
        System.out.println(ballClassC.getSimpleName());
    }
}
class Ball{}

result:

class com.tx.test.reflection.Ball
com.tx.test.reflection.Ball
Ball

It features three ways:

1, class .getClass (): to obtain a clear need to use the class object instance.

2, class .class: import process require explicit class operation.

3, Class.forName (): by using the class name described in a character string (character string by using a very convenient, is not preferred when considering development of complex).

Reflection and plant design

The plant was originally designed to solve the coupling, static coupling plant design can be resolved to some extent, but as long as there is the new keyword coupling inevitable.

Here Insert Picture Description

Using a static factory design flaws in the realization, when more than one sub-class interface, there are hundreds, thousands, the Each class created for a clearly impossible, too much trouble, but the use of reflection can dynamic plant design, need only implement the same interface, a common method can be realized instantiate operation.

Example:

public class TestTrendsFactory {
    public static void main(String[] args) throws Exception {
        IBall ball = Factory.getInstance("com.tx.test.reflection.BasketBallImpl");
        if (ball != null) {	
            ball.play("篮球");
        }
    }
}

interface IBall {
    /**
     * 玩球
     *
     * @param msg 球的种类
     */
    void play(String msg);
}

class BasketBallImpl implements IBall {

    @Override
    public void play(String msg) {
        System.out.println("【球的种类】玩" + msg + "!!!");
    }
}

class Factory {
    private Factory() {
    }

    /**
     * 根据传入的类进行实例化操作
     * @param msg 传入的类
     * @return  返回实例化后的对象
     */
    public static IBall getInstance(String msg) {
        IBall ball;
        try {
            ball = (IBall) Class.forName(msg).getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            return null;
        }
        return ball;
    }
}

result:

【球的种类】玩篮球!!!

Design of the single reflection Example

Singleton design is the core essence of being a JVM process is only allowed to have one instance.

Here Insert Picture Description

Example: when a plurality of threads operate lazy instantiation equation

public class TestSingleton {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
              Animal animal = Animal.getInstance();
            }).start();
        }
    }
}

class Animal {
    private static Animal animal;

    private Animal() {
        System.out.println("懒汉式单例设计多线程测试!!!");
    }

    public static Animal getInstance() {
        if (animal == null) {
            animal = new Animal();
        }
        return animal;
    }
}

result:

懒汉式单例设计多线程测试!!!
懒汉式单例设计多线程测试!!!
懒汉式单例设计多线程测试!!!
懒汉式单例设计多线程测试!!!
懒汉式单例设计多线程测试!!!

When the plurality of single threads lazy case design operation can not be implemented in a single embodiment.

Solution: adding synchronized on the method, but in a multithreaded state of high concurrency, it will seriously affect performance.

Here Insert Picture Description

Example: added in the synchronized method.

public class TestSingleton {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
              Animal animal = Animal.getInstance();
            }).start();
        }
    }
}

class Animal {
    private static Animal animal;

    private Animal() {
        System.out.println("懒汉式单例设计多线程测试!!!");
    }

    public synchronized static Animal getInstance() {
        if (animal == null) {
            animal = new Animal();
        }
        return animal;
    }
}

result:

懒汉式单例设计多线程测试!!!

Solution two: use problem solving internally synchronized and reflection method.

The reason why the null value then determines the synchronization code block is to ensure that only the first thread will enter operation for example, in a case where a plurality of threads, when the first instantiated into the outside of the null value also determines become (even if there is a delay of only a few threads will enter), directly after the thread returns false.

Here Insert Picture Description

Example:

public class TestSingletonInterior {
    public static void main(String[] args) {

    }
}

class Person {
    private static Person person;

    private Person() {
        System.out.println("内部synchronized懒汉式单例设计!!!");
    }

    public static Person getInstance() {
        if (person == null) {
            synchronized (Person.class) {
                if (person == null) {
                    person = new Person();
                }
            }
        }
        return person;
    }
}

result:

内部synchronized懒汉式单例设计!!!

Dynamic proxy mode

Class structure information

Structural information can be obtained by the class Class.

method Explanation
public Class<?>[] getInterfaces() Get all of the parent Interface
public Package getPackage() Get the name of the class where the package
public Class<? super T> getSuperclass() Access the inherited parent class information

Example:

public class TestProgramData {
    public static void main(String[] args) {
        Class<?> clazz = MessageImpl.class;
        System.out.println("clazz->"+clazz.getName());
        System.out.println("getPackage()->"+clazz.getPackage().getName());
        System.out.println("getSuperclass()->"+clazz.getSuperclass().getName());
        System.out.println("getInterfaces()->"+ Arrays.toString(clazz.getInterfaces()));

    }
}
interface IMessage{}
interface IMessageData{}
abstract class AbstractMessage implements IMessage,IMessageData{}
class MessageImpl extends AbstractMessage implements IMessage,IMessageData{}

result:

clazz->com.tx.test.reflection.MessageImpl
getPackage()->com.tx.test.reflection
getSuperclass()->com.tx.test.reflection.AbstractMessage
getInterfaces()->[interface com.tx.test.reflection.IMessage, interface com.tx.test.reflection.IMessageData]
Published 61 original articles · won praise 0 · Views 2176

Guess you like

Origin blog.csdn.net/sabstarb/article/details/104701822