Java Reflection Mechanism Example _java

Source: Internet
Author: User
Tags reflection

Java Reflection

The Java reflection mechanism is in the running state, for any class, all the properties and methods of the class can be known, and any one of its methods and properties can be invoked for any object; This dynamically acquired information, and the function of the method that dynamically invokes the object, is called the reflection mechanism of the Java language.

Copy Code code as follows:

Package c_20130313;

Import Java.lang.reflect.Method;

Class User

{

private String name;

Public User () {}

Public User (String name)

{

This.name=name;

}

public void Say ()//No parameter method

{

System.out.println ("Hello, my name is +name+"!) ");

}

public void Say (String str)//method with parameters

{

System.out.println ("Hello, my name is +name+"!) "+str+", I am a method of participation! ");

}

}

/**

* @author Lxa

* The simplest example of reflection

*/

public class Reflection

{

public static void Main (string[] args) throws Exception

{

Class c=class.forname ("c_20130313_ reflection.") User ");//Find the corresponding class by reflection

Method M1=c.getmethod ("say")//Find the name of the say, and no parameters

Method M2=c.getmethod ("Say", string.class);//Find a way to have a name called Say and have a String type parameter

M1.invoke (C.newinstance ())//Note that newinstance () calls the parameterless construction method!!!

M2.invoke (New User ("Liu Xianhan"), "haha");//Instantiate an object by means of a parameter constructor

}

}

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.