Java Reflection Mechanism Demo (v)-Get and Invoke methods in a class

Source: Internet
Author: User
Tags reflection

The main reason for this demo before using the reflection mechanism to manipulate properties is because in the. class file bytecode, the method is in front of the property.

1, obtain a method in a class

Let's look at the method and run the results. Get all the methods using the class Getmethos () method.

Classes to get:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546 packagecom.aaron.reflect;publicclassHeros {    privateString name;//名字    privateString type;//类型    privateintcamp;//0,近卫;1,天灾        public Heros(){}    publicHeros(String name, String type, intcamp) {        super();        this.name = name;        this.type = type;        this.camp = camp;    }    publicString getName() {        returnname;    }     publicvoidsetName(String name) {        this.name = name;    }    publicString getType() {        return type;    }    publicvoidsetType(String type) {        this.type = type;    }    publicint getCamp() {        returncamp;    }    publicvoidsetCamp(intcamp) {        this.camp = camp;    }    @Override    publicString toString() {        return"Heros [\n name="+ name + ", \n type="+ type + ", \n camp="+ camp + "\n]";    }    }

The Hero class contains three properties, and corresponding getter and setter methods. There's also a ToString method. This is a very common pojo.

Test class:

12345678910111213 packagecom.aaron.reflect;importjava.lang.reflect.Method; publicclassDemo5 {    publicstaticvoidmain(String[] args) {        Class<?> herosClass = Heros.class;        Method[] methods = herosClass.getMethods();        for(Method method : methods) {            System.out.println(method);        }    }}

Theoretically, we'll get all the getter and setter, and then the ToString method

Operation Result:

123456789101112131415 publicvoidcom.aaron.reflect.Heros.setType(java.lang.String)publicintcom.aaron.reflect.Heros.getCamp()publicvoidcom.aaron.reflect.Heros.setCamp(int)publicjava.lang.String com.aaron.reflect.Heros.toString()public java.lang.String com.aaron.reflect.Heros.getName()publicvoidcom.aaron.reflect.Heros.setName(java.lang.String)publicjava.lang.String com.aaron.reflect.Heros.getType()publicfinalvoidjava.lang.Object.wait(long,intthrowsjava.lang.InterruptedExceptionpublicfinalnativevoidjava.lang.Object.wait(longthrowsjava.lang.InterruptedExceptionpublicfinal voidjava.lang.Object.wait() throwsjava.lang.InterruptedExceptionpublicbooleanjava.lang.Object.equals(java.lang.Object)publicnativeintjava.lang.Object.hashCode()publicfinal nativejava.lang.Class java.lang.Object.getClass()publicfinalnativevoidjava.lang.Object.notify()publicfinalnativevoidjava.lang.Object.notifyAll()

However, it is a list of such a large pile.

Take a closer look at the return method and return the methods owned by the object class. Because our Pojo class inherits the Java.lang.Object class by default. , such as GetClass (), Equals ().

Using GetMethods (), this method returns an array containing some method objects that have been introduced to represent the object of a method, which is the result of abstracting the methods in the class.

These objects reflect the class or interface represented by the class object, including, of course, those classes or interfaces declared by the class or interface and inherited from the superclass and the hyper-interface. An example to explain:

For example, using GetMethods () to obtain an integer class method, the parent class of Integer, all methods of number, and the method of the parent object of number are obtained.

This returns an array that includes all ( public ) member methods inherited from the object class. The elements in the returned array are not sorted. If this class object represents a class or interface that does not have a public member method, or represents a primitive type or represents void, an array of length 0 is returned.

2, calling methods in the class

Give a demo directly, note the parameters.

1234567891011121314151617181920 packagecom.aaron.reflect;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;publicclassDemo5 {    publicstaticvoidmain(String[] args) {        Class<?> herosClass = Heros.class;        try{            Method m1 = herosClass.getMethod("setName",String.class);            Method m2 = herosClass.getMethod("getName");            Object userInfo = herosClass.newInstance();            m1.invoke(userInfo,"影魔");            System.out.println("调用set方法:"+userInfo);            System.out.println("调用get方法:"+m2.invoke(userInfo));        catch(Exception e) {            e.printStackTrace();        }    }}

Operation Result:

12345678 调用set方法:Heros [ name=影魔, type=null, camp=0]调用get方法:影魔

  

  

  

Java Reflection Mechanism Demo (v)-Get and Invoke methods in a class

Related Article

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.