Summary of dynamic attributes in Java

Source: Internet
Author: User

 

Opening part:

Start with the example. For example, there is a class helloworld, which prints Hello world using the method sayhello.
Helloworld. Java

{
Function onclick ()
{
DP. Sh. toolbar. Command ('viewsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> View plain {
Function onclick ()
{
DP. Sh. toolbar. Command ('copytoclipboard', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> copy to clipboard {
Function onclick ()
{
DP. Sh. toolbar. Command ('printsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> Print {
Function onclick ()
{
DP. Sh. toolbar. Command ('about', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html ">?
  1. Package com. test;
  2. Public class helloworld {
  3. Public void sayhello (){
  4. System. Out. println ("Hello World ");
  5. }
  6. }
package com.test;public class HelloWorld {    public void sayHello() {        System.out.println("Hello World");    }}

Generally, you can call it using the following methods:

{
Function onclick ()
{
DP. Sh. toolbar. Command ('viewsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> View plain {
Function onclick ()
{
DP. Sh. toolbar. Command ('copytoclipboard', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> copy to clipboard {
Function onclick ()
{
DP. Sh. toolbar. Command ('printsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> Print {
Function onclick ()
{
DP. Sh. toolbar. Command ('about', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html ">?
  1. Helloworld = new helloworld ();
  2. Helloworld. sayhello ();
        HelloWorld helloWorld = new HelloWorld();        helloWorld.sayHello();

But in many cases, we need to use a more flexible method for calling. For example, configure the class name in the configuration file and then automatically call it in the program. Perform specific operations before and after the method is called. Those who have used JSF, struts, or spring will not be unfamiliar with this: JSF can bind page elements and events, spring can automatically set attribute values for objects and so on through the configuration file without using the new statement. In recent years, the widely used Di, AOP, and other technologies mostly use the dynamic attributes of Java.

The following describes the dynamic attributes of Java in detail.

First, let's briefly introduce several dynamic-related classes and interfaces in Java:

Class or Interface Name Description
Java. Lang. Class It contains the structure information (constructor, field, method, annotation, etc.) of the class and corresponding operation methods.
Java. Lang. Reflect. accessibleobject Field, method, constructor, and other class base classes, mainly provide permission control mechanisms
Java. Lang. Reflect. Method Contains the structure information and method operations of the method.
Java. Lang. Reflect. Field Structure Information and attribute operations that contain attributes
Java. Lang. Reflect. Constructor Contains the structure information of the constructor and the operations of the constructor.
Java. Lang. annotation. Annotation Interface. Annotation information appended to classes, properties, and methods
Java. Lang. Reflect. Proxy A very important class of the dynamic proxy function. It can be used with invocationhandler to implement the dynamic proxy function.
Java. Lang. Reflect. invocationhandler An important API of the dynamic proxy function. It implements the dynamic proxy function together with the proxy.

Java uses the reflection API to obtain information such as method, field, and annotation from the Java class, which can be accessed or executed. These APIs are all in the Java. Lang. Reflect package, and they are not very difficult to use.

Acquisition of class structure information and instance generation

You can obtain the class information in several ways:
Object Reference:
This. getclass ();
OBJ. getclass ();

Reference by Class Name:
For example: helloworld. Class

Obtained through class. forname (string classname)
For example, class. forname ("com. Test. helloworld ");

After obtaining the class information, you can perform various operations.

{
Function onclick ()
{
DP. Sh. toolbar. Command ('viewsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> View plain {
Function onclick ()
{
DP. Sh. toolbar. Command ('copytoclipboard', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> copy to clipboard {
Function onclick ()
{
DP. Sh. toolbar. Command ('printsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> Print {
Function onclick ()
{
DP. Sh. toolbar. Command ('about', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html ">?
  1. Try {
  2. Class helloworldclass = Class. forname ("com. Test. helloworld ");
  3. Helloworld = (helloworld) helloworldclass. newinstance ();
  4. Helloworld. sayhello ();
  5. } Catch (classnotfoundexception E1 ){
  6. // Todo
  7. } Catch (instantiationexception e ){
  8. // Todo
  9. } Catch (illegalaccessexception e ){
  10. // Todo
  11. }
        try {            Class helloWorldClass = Class.forName("com.test.HelloWorld");            HelloWorld helloWorld = (HelloWorld)helloWorldClass.newInstance();            helloWorld.sayHello();        } catch (ClassNotFoundException e1) {            //TODO        } catch (InstantiationException e) {            //TODO        } catch (IllegalAccessException e) {            //TODO        } 

The class. forname method can obtain the Class Object Based on the specified class name. The class. newinstance () method can generate instances for the class. They have several usage methods. The specific usage method is not described here.

Method: Obtain and execute the method.

You can use class. getmethod or class. getmethods to obtain method information. You can also use the class. Invoke method to directly execute the obtained method.

{
Function onclick ()
{
DP. Sh. toolbar. Command ('viewsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> View plain {
Function onclick ()
{
DP. Sh. toolbar. Command ('copytoclipboard', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> copy to clipboard {
Function onclick ()
{
DP. Sh. toolbar. Command ('printsource', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html "> Print {
Function onclick ()
{
DP. Sh. toolbar. Command ('about', this); Return false;
}
} "Href =" http://www.lifevv.com/tenyo/doc/20070803142643181.html ">?
  1. Method sayhellomethod = helloworld. Class. getmethod ("sayhello", new class [] {});
  2. Sayhellomethod. Invoke (helloworld, null );
    Method sayHelloMethod = HelloWorld.class.getMethod("sayHello", new Class[]{});    sayHelloMethod.invoke(helloWorld, null);

Class. getmethod: gets the method based on the method name and parameter type. The first parameter is the method name (string), and the second parameter is the method parameter type (class []). If there is no parameter, you can set it to null or empty class []. For example, if a method has two parameters: string and integer, the parameters of 2nd are new class [] {string. Class, integer. Class }. Class. getmethod can only obtain public methods. To obtain all types of methods, you can use class. getdeclaredmethod.
Method. Invoke: Execution method. The first parameter is of the method type. The second parameter is the parameter value (object []) that needs to be transferred to the method. If no parameter exists, it can be set to null.
Method. setaccessible: The method parent class accessibleobject. setaccessible (Boolean) can be used to set access permissions for methods. For example, sayhellomethod. Invoke can only execute non-private methods in principle. However, if setaccessible (true) is set for the private method, this method can also be executed.

Attribute: Field Acquisition and attribute value setting and assignment (Set/get)

Field is basically the same as method. You can use class. getfield (fieldname), Class. getfields, class. getdeclaredfield, class. getdeclaredfields, and so on. You can also reset the access permission through the field. setaccessible method. For details, refer to the method section above.

The above describes the basic methods for accessing class, method, field, and so on by using Java's reflect function. In addition, you can obtain the annotation information attached to the class, method, and field ). For more information about annotation, see:
Introduction to Java annotation (1)
Java annotation customization (2)
Application of Java annotation-dynamic parsing of annotation during runtime (3)

In addition, we will introduce the dynamic proxy function of Java through another article.

Collected on:

Http://www.lifevv.com/tenyo/doc/20070803142643181.html

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.