Java reflection mechanism

Source: Internet
Author: User
Tags java se

Course Java object-oriented programming experiment name reflection mechanism page

Class Subtotal

First, the purpose of the experiment

Mastering the use of reflection mechanisms

Second, the experimental environment

1, microcomputer one set

2.WINDOWS operating system , Java sdk,eclipse development environment

Iii. contents of the experiment

1, design a student class, including the name, age attributes and speaking methods.

2, write a program, through the reflection mechanism, create the object of the student class, and its name and age attributes to read and write, and finally call its method of speech.

3, design a production class, including a processing method, the production of shoes;

4, for the production class to design a proxy class, the request to receive intermediary fees 1000 yuan.

5, write test procedures.

6, the use of dynamic Proxy to create a proxy class, the same charge 1000 yuan.

Iv. Experimental Steps and Results

1, design a student class, including the name, age attributes and speaking methods.

Package com.student;

public class Student {

private String name;

private int age;

Public String GetName () {

return name;

}

public void SetName (String name) {

System.out.println ("Call SetName method");

THIS.name = name;

}

public int getage () {

return age;

}

public void Setage (int.) {

This.age = age;

}

Public Student () {

Super ();

System.out.println ("default constructor method");

}

Public Student (String name, int.) {

Super ();

THIS.name = name;

This.age = age;

}

Public String toString () {

Return "Student [name=" + name + ", age=" + Age + "]";

}

private void Stuspeak () {

System.out.println (GetClass (). GetName () + "say" hi! Java Reflection __by shenxiaolin! ' ");

}

}

2, write a program, through the reflection mechanism, create the object of the student class, and its name and age attributes to read and write, and finally call its method of speech.

The test code looks like this:

Package com.student;

Import java.lang.reflect.InvocationTargetException;

Import Java.lang.reflect.Constructor;

Import Java.lang.reflect.Field;

Import Java.lang.reflect.Method;

public class Stureflectiontest {

public static void Main (string[] args) {

try {

1, obtain the corresponding student class

Class c=class.forname ("com.student.Student");

2. Create an object using the non-parametric construction method

Student stu= (Student) c.newinstance ();

System.out.println ("Successfully created a student object! ");

3. Calling private properties

Field Namefield=c.getdeclaredfield ("name");

Namefield.setaccessible (TRUE);//cancels access checks on the name field

Namefield.set (Stu, "Zhangsan");//Set the value of the NameField member variable of the Stu object to Zhangsan

System.out.println (">>> name is:" +namefield.get (Stu));//Gets the value of the NameField member variable of the Stu object

Field Agefield=c.getdeclaredfield ("Age");

Agefield.setaccessible (TRUE);

Agefield.setint (Stu, 20);

System.out.println (">>> Age is:" +agefield.getint (Stu));

SYSTEM.OUT.PRINTLN ("successfully read and write names and age attributes!");

Method Method2=c.getdeclaredmethod ("Stuspeak", (class[]) null);

Method2.setaccessible (TRUE);

Method2.invoke (Stu,null);

System.out.println ("Talking method of Successful Call Object!");

} catch (ClassNotFoundException e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Instantiationexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Illegalaccessexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Nosuchfieldexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (SecurityException e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (Nosuchmethodexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (IllegalArgumentException e) {

TODO auto-generated Catch block

E.printstacktrace ();

} catch (InvocationTargetException e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

}

The results of the operation are as follows:

3, design a production class, including a processing method, the production of shoes.

(1) First design a production of a batch of shoes function interface (Shoesfactory.java)

Package com.produce;

First, define an interface that can complete the production of shoe functions.

Public interface Shoesfactory {

Has the function of producing shoes

void Productshoes ();

}

(2) Design a production class (Producer.java) to inherit the above interface, including a processing method, the production of shoes.

Package com.produce;

Producer is a production class that contains a processing method that manufactures shoes

public class Producer implements Shoesfactory {

public void Productshoes () {

System.out.println ("Production shoe company successfully produced a batch of shoes");

}}

4, for the production class to design a proxy class (Agency.java), the request to receive intermediary fees 1000 yuan.

Package com.produce;

For the production class producer design a proxy class agency, charged 1000 yuan intermediary fee.

public class Agency implements shoesfactory{

Private Shoesfactory SF;

Agents do not produce their own shoes, need to find a real service to do the company

Public Agency (shoesfactory SF) {

Super ();

THIS.SF = SF;

}

public void Productshoes () {

SYSTEM.OUT.PRINTLN ("agency charge 1000 yuan for agency fees");

Sf.productshoes ();//commissioned a real service company to produce shoes

}

}

5, write the test procedure (Customertest.java), the customer through the agent company produced a number of shoes.

Package com.produce;

The customer produced a group of shoes through the agency.

public class Customertest {

public static void Main (string[] args) {

Shoesfactory sf=new Agency (New Producer ());

Sf.productshoes ();

}

}

The results of the test run are as follows:

6, the use of dynamic Proxy to create a proxy class, the same charge 1000 yuan.

(1) First define a Invocationhandler interface: The processing class of the proxy class needs to implement this interface, there is only one method in this interface.

Package com.produce;

Import Java.lang.reflect.Method;

Invocationhandler interface: The processing classes of the proxy class all need to implement this interface, there is only one method in this interface.

Public interface Invocationhandler {

public object Invoke (object Proxy,method Method, object[] args) throws Throwable;

}

(2) Create a dynamic proxy class with JDK support for dynamic proxies, as shown in the following code:

Package com.produce;

Import Java.lang.reflect.Method;

Import Java.lang.reflect.Proxy;

Import java.lang.reflect.*;

Dynamic proxy Classes

public class Dynamicagency implements Invocationhandler, java.lang.reflect.invocationhandler{

Target Object

Private Object target;

public object Newproxyinstance (object target) {

This.target=target;

The first parameter is: the class loader that defines the proxy class

The second argument is: The list of interfaces to be implemented by the proxy class

The third parameter is: the call handler that assigns the method call

Return Proxy.newproxyinstance (This.target.getClass (). getClassLoader (),

This.target.getClass (). Getinterfaces (), this);

}

public object invoke (object agency, method method, object[] args)

Throws Throwable {

Object Result=null;

SYSTEM.OUT.PRINTLN ("Dynamic agent charged 1000 yuan intermediary fee");

try {

You can add additional code before a method call on the target object ...

Result=method.invoke (This.target, args);

To invoke the corresponding method on the target object by reflection

You can add additional code after a method call on the target object ...

} catch (Exception e) {

Throw e;

}

return result;

}

}

(3) The calling test code on the client is changed to the following way:

Package com.produce;

The customer produced a group of shoes through the agency.

public class Customertest {

public static void Main (string[] args) {

Static proxy

Shoesfactory sf=new Agency (New Producer ());

Sf.productshoes ();

Dynamic Agent

Dynamicagency dyagency=new dynamicagency ();

Shoesfactory sf2= (shoesfactory) dyagency.newproxyinstance (New Producer ());

Sf2.productshoes ();

}

}

(4) The test result is:

V. Summary of the Experiment

1. The experiment was completed on time and in quantity.

2. Through this experiment, I have deepened my knowledge of reflection, reflection refers to a class of self-describing and self-control applications. This kind of application uses some mechanism to realize its own behavior description (self-representation) and monitoring (examination), and can adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.

3. To create an object using the parameter construction method:

The 1th step gets the class object corresponding to the specified class.

The 2nd step is to get the constructor class object that satisfies the specified parameter type requirements through the class object.

The 3rd step calls the Newinstance method that specifies the constructor object, passing in the corresponding parameter value and creating the object.

4. Static proxies are the role of intermediaries between the client and the target object. The principle of dynamic proxies is to dynamically create proxy objects for the target class as needed while the program is running. The Java SE API provides classes and interfaces for dynamic proxy support in the Java.lang.reflect package.

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.