Java Reflection Example

Source: Internet
Author: User

This article: http://www.cnblogs.com/yydcdut/p/3845430.html

Basic Introduction to 1.Java reflection

Java's reflection is powerful, passing class. Can generate the class dynamically, get all the information of this class, including the properties, methods and constructors. Can even get content from its parent or parent interface.

The Java reflection mechanism mainly provides the following features:

    • Infer at random the class to which an object belongs;
    • Constructs an arbitrary class object at execution time;
    • Infer the member variables and methods that a class can have at execution time;
    • A method of invoking an arbitrary object at execution time;
    • Generates a dynamic agent.

In the JDK, the Java reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package.

    • Class: Represents a Class.

    • Field class: Represents a member variable of a class (a member variable is also called a property of a class).

    • Method class: Methods that represent classes.

    • Constructor class: Represents the construction method of a class.

    • Array class: Provides a static way to create arrays dynamically and to access array elements.


Package Com.hh.reflect;import Java.lang.reflect.constructor;import Java.lang.reflect.method;public class ClassDemo { public static void Main (string[] args) throws Exception {//11111system.out.println ("========11111=========="); Person Person1 = new person (); Class C1 = Person1.getclass (); Person Person2 = new person (); Class C2 = Person2.getclass (); SYSTEM.OUT.PRINTLN (C1 = = C2);//22222system.out.println ("========22222=========="); Class C3 = Person.class; SYSTEM.OUT.PRINTLN (C1 = = C3);//33333system.out.println ("========33333=========="); Class C4 = class.forname ("Com.hh.reflect.Person"); SYSTEM.OUT.PRINTLN (C1 = = C4); Constructor CO = c4.getconstructor (null); Object obj = co.newinstance (null); Method m = C4.getmethod ("show", null); M.invoke (obj, null);}}

Person class:

Package Com.hh.reflect;public class Person {public void show () {System.out.println ("person------->show ()");}}

Execution Result:

========11111==========true========22222==========true========33333==========trueperson------->show ()

Because there is only one Person.class file in the project, the objects obtained by reflection are the same.


2. One of the ways in which reflection is used
If there are two classes: 1. Classa.java 2.classb.java

public class ClassA {public void Show (String str) {System.out.println (str + "ClassA------>show ()");}}

public class ClassB {public void Show (String str) {System.out.println (str + "ClassB------>show ()");}}

Add a configuration file who.txt. The contents are as follows:

Class=com.hh.reflect.classbmethod=show

The main class Reflecttest.java is this

public class Reflecttest {public static void main (string[] args) throws Exception {Properties prop = new Properties (); FileReader FR = new FileReader ("Who.txt");p Rop.load (FR); Fr.close (); String className = Prop.getproperty ("class"); String methodName = Prop.getproperty ("method");//Gets the type of object Class c = Class.forName (className);// Creates a new object by default construction method Constructor CO = C.getconstructor (null), Object obj = Co.newinstance (null),//method to get object m = C.getmethod (methodName, "Hello". GetClass ());//method that invokes the object M.invoke (obj, "Hello");}}

When changing the configuration file, make the class attribute a different value. The results of the program execution are not the same:

①class=com.hh.reflect.classa

Hello ClassA------>show ()
②class=com.hh.reflect.classb

Hello ClassB------>show ()
where "Hello" is the number of references passed to the show (String str) method

The principle of the above reflection sample. Used by the Java framework, such as Hibernate, Spring, and so on: First parse the configuration file with XML, and then get all the information of the class through the Java reflection mechanism.


Java Reflection Example

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.