Java Reflection Summary and use __java

Source: Internet
Author: User
What is Reflection

That's what the official paragraph says.

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of application s running in the Java virtual machine.

What does that mean? Reflection is typically used for programs that need to be able to check or modify the run-time behavior of an application running in a Java virtual machine.

Not very understood, let's say what reflex can do. Reflection can dynamically generate an instance of a class at run time. Reflection can get any of the variables of a class at run time and modify the value of the variable. Reflection can execute any method of a class at run time. How to use reflection

Let's talk about how to use the above situation.

Let's first define a Com.reflect.Demo.java to do our follow-up experiments.

Package com.reflect;
public class Demo {public

    String pubstr = "public_string";
    Private String pristr = "private_string";

    private string Getpristr (String testparam) {
        pubstr = Testparam;
        return pristr;
    }

    Private String Getpristr () {return
        pristr;
    }

    Public demo () {

    }

    private Demo (String pristr) {
        this.pristr = pristr;
    }

    @Override public
    String toString () {return
        "demo{" +
                "pubstr= '" + pubstr + "\
                " + ", pristr=" + PriS TR + ' \ ' +
                '} ';
    }

to dynamically generate an instance of a class at run time
The first step of reflection is to get class classes, there are generally 3 kinds of writing class
DemoClass = Class.forName ("Com.reflect.Demo");
DemoClass = Demo.class;
DemoClass = new Demo (). GetClass ();

Gets the parameterless constructor
constructor constructor = Democlass.getdeclaredconstructor ();
Setting can access
constructor.setaccessible (true);
Creates an instance
Object demo = Constructor.newinstance () based on the construction method;

Gets a parameter constructor
constructor constructor1 = Democlass.getdeclaredconstructor (string.class);
Setting can access
constructor1.setaccessible (true);
Creates an instance
Object demo1 = constructor1.newinstance ("I am String") based on the construction method;

A common way to get an instance of a class is described below

    /** * Use reflection to get an instance of a class through the default constructor * * @param className * @return/public static Object Getob
            Jectinstance (String className, Object ... args) {try {class[] classes = new Class[args.length];
            for (int i = 0; i < args.length i++) {Classes[i] = Args[i].getclass ();
            Class objclass = Class.forName (className);
            Constructor constructor = Objclass.getdeclaredconstructor (classes);
            Constructor.setaccessible (TRUE);
        Return constructor.newinstance (args);
        catch (ClassNotFoundException e) {e.printstacktrace ();
        catch (Nosuchmethodexception e) {e.printstacktrace ();
        catch (Instantiationexception e) {e.printstacktrace ();
        catch (Illegalaccessexception e) {e.printstacktrace ();
        catch (InvocationTargetException e) {e.printstacktrace (); RetUrn new Object (); }
get any of the variables for a class at run time and modify the value of the variable

The following code tells you how to get the variable (PRISTR) of an instance of Demo.java and assign a value to it.

An instance of the parameterless construction method new, where the PRISTR value is private_string
Demo demo = new Demo ();
Get the Demo class
class DemoClass = Demo.getclass ();
Gets the field 
field Pristrfield = Democlass.getdeclaredfield ("Pristr") of the Pristr;
Setting can access
pristrfield.setaccessible (true);

Take the value of PRISTR
//To take a demo of this instance of the PRISTR, so you need to pass the demo
Object pristrvalue = Pristrfield.get (demo); 

Modify the value of Pristr
//To modify the demo this instance, so you need to pass in the demo

Here's a common way to get a property

    /** * Get the value of a variable * @param obj to be valued class * @param the variable name of the variable fieldName the value to be fetched * @return * public static object GetFieldValue (Object obj, String fieldName) {try {Field field = Obj.getclass ()
            . Getdeclaredfield (FieldName);
            Field.setaccessible (TRUE);
        return Field.get (obj);
        catch (Nosuchfieldexception e) {e.printstacktrace ();
        catch (Illegalaccessexception e) {e.printstacktrace ();
    return new Object ();
     /** * Sets the value of a variable for a class * @param obj * @param fieldName * @param fieldvalue * @return
            */public static Boolean SetFieldValue (Object obj, String fieldName, Object fieldvalue) {try {
            Field field = Obj.getclass (). Getdeclaredfield (FieldName);
            Field.setaccessible (TRUE);
            Field.set (obj, fieldvalue);
        return true;
     catch (Nosuchfieldexception e) {       E.printstacktrace ();
        catch (Illegalaccessexception e) {e.printstacktrace ();
    return false; }
any method that executes a class at run time

The following code tells you how to get a method of Demo.java (GETPRISTR) and call this method.

An instance of the parameterless construction method new, where the PRISTR value is private_string
Demo demo = new Demo ();
Get the Demo class
class DemoClass = Demo.getclass ();

Gets the corresponding method method 
Pristrmethod = Democlass.getdeclaredmethod ("Pristr") of the parameterless getpristr;
Setting can access
pristrmethod.setaccessible (true);
Call this method
Object pristr = Pristrmethod.invoke (obj);

Gets a parameter getpristr corresponding to method 
priStrMethod1 = Democlass.getdeclaredmethod ("Pristr", string.class);
Setting can access
pristrmethod1.setaccessible (true);
Call this method
Object priStr1 = Pristrmethod1.invoke (obj, "I am Testparam");

Here's a common way to invoke objects

    /**
     * Call a method
     * @param obj
     * @param methodname *
     @param args
     * @return
    /public static Object Invokmethod (Object obj, String methodname, Object ... args) {
        try {
            class[] classes = new Class[args.length] ;
            for (int i = 0; i < args.length i++) {
                Classes[i] = Args[i].getclass ();
            }
            Method method = Obj.getclass (). Getdeclaredmethod (methodname, classes);
            Method.setaccessible (true);
            Method.invoke (Obj,args);
            return Method.invoke (obj, args);
        catch (Illegalaccessexception e) {
            e.printstacktrace ();
        } catch (Nosuchmethodexception e) {
            E.printstacktrace ();
        } catch (InvocationTargetException e) {
            e.printstacktrace ();
        }
        return new Object ();
    }

More usage can refer to DEMO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.