Java Reflection Example

Source: Internet
Author: User

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

Basic Introduction to 1.Java reflection

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

The Java reflection mechanism mainly provides the following features:

    • Determine the class to which any object belongs at run time;
    • Constructs an object of any class at run time;
    • Determine the member variables and methods of any class at run time;
    • A method of invoking any object at run 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 method for dynamically creating arrays and accessing 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 ()");}}

Operation 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 uses of reflection
Suppose 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 with the following content:

Class=com.hh.reflect.classbmethod=show

The main class Reflecttest.java is like 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 you modify a configuration file so that the class's properties are different values, the program runs differently:

①class=com.hh.reflect.classa

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

Hello ClassB------>show ()
where "Hello" is a parameter passed to the show (String str) method

The principle of this small example of reflection is commonly 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.


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.