On Java's reflection mechanism

Java's reflection mechanism is particularly suitable for large-scale projects, especially the development of multi-purpose projects. Because it greatly reduces the time to load static class at compile time and reduces the initial memory consumption.

 

Why should there be reflection

1. when it comes to certain applications, we often need to upgrade in order to increase the dynamic modification capabilities and upgrade all need to be changes to the source code is compiled in a static system, which means that one liter level is necessary for the entire source code is compiled once. Small program compiled, better said, but if it is a large program, the compiler once to several hours or even days to complete, so it is clear that purely static programming mode is not suitable. And Java is a static language, in order to make up for this shortcoming, there is a reflex mechanism.

2. Java more is applied to the server program, and a program on the server has a very important feature is not turned off; even when turned off, but also advance notification to the user. So, if you want to upgrade the system at this time, it is necessary to ensure the normal operation of other functions within the system, but also to ensure that measures to upgrade, then you can use reflection to achieve.

3. To make the program more clear, and the main functions of the program are separated to facilitate subsequent management.

 

Application of reflection

• Online update antivirus software virus database

• Build JDBC Data Bridge (Class.forName ( "database-driven package class name"))

• increased application functionality

• Analyze the generic essence

• analysis program, looking for bug

 

There are three ways to achieve reflection

• get class types, while loading class Class class = Class.forName ( "SomethingName")

• known class objects obtained by the object class to which it belongs Class class = new Demo (). GetClass ()

• directly its class type of class Class class = Demo.Class

 

Reflection type

• Class class, the class level for reflection treatment;

• Field class member variables for processing the reflection level;

• Method class, a method for handling order reflection;

• Constructor class, the class constructor for processing reflected;

 

Examples of small reflection (to manage the system as an example)

import java.lang.reflect.Method;

import java.util.Scanner;

 

class Main {

    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static void main(String[] args) {

        System.out.println("||Add||   ||Remove||   ||Sort||   ||Change||   ||Seek||");

        System.out.print("Input your choose:");

        Scanner scanner = new Scanner(System.in);

        String string = scanner.nextLine();

        scanner.close();

        try{

            Class class1 = Class.forName (string); // get loaded while class category

            Method method = class1.getDeclaredMethod("command", String.class);

            method.invoke(class1.newInstance(), "something");

        }

        catch(Exception e){

            e.printStackTrace ();

        }

    }

}

 

class Add implements Common{

    public void command(String string){

        System.out.println("Add Completed!");

    }

}

 

class Remove implements Common{

    public void command(String string){

        System.out.println("Remove completed!");

    }

}

 

class Sort implements Common{

    public void command(String string){

        System.out.println("Sort completed!");

    }

}

 

class Change implements Common{

    public void command(String string){

        System.out.println("Change completed!");

    }

}

 

class Seek implements Common{

    public void command(String string){

        System.out.println("Seek completed!");

    }

}

 

interface Common {

    public void command(String string);

}

 

Look through the generic reflection

The generic nature of the role of Java in order to prevent input errors compile phase, the type of reference error, parameter error. And after compiling, Java does not exist in the concept of generics. Here, the verification can be reflected.

 

import java.lang.reflect.Method;

import java.util.ArrayList;

 

public class Test {

    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static void main(String[] args){

        ArrayList<String> arrayList = new ArrayList<String>();

        arrayList.add("string");

        System.out.println(arrayList.size());

        Class class1 = arrayList.getClass();

        try {

            Method method = class1.getMethod("add", Object.class);

            method.invoke(arrayList, 100);

            System.out.println(arrayList.size());

        }

        catch (Exception e){

            e.printStackTrace ();

        }

        ArrayList arrayList2 = new ArrayList();

        Class class2 = arrayList2.getClass();

        System.out.println(class1 == class2);

    }

}

Results are shown as 1,2, true, which indicates that by reflection, int value type is successfully added to the initial set of generic String among true and the last two sets of said compiled class types are the same, no the presence of generics.

 

Guess you like

Origin www.cnblogs.com/fusiji/p/11409839.html