Dynamic class loading Using Reflection

Source: Internet
Author: User

Dynamic class loading Using Reflection

Bromon originality, please respect copyright

Recently, I wrote a mobile value-added project in Chengdu, where I am responsible for the backend server. The function is very simple. A mobile phone user opens a socket through GPRS to connect to the server, and I will respond based on the data transmitted by the user. Everyone who has done similar projects knows that a communication protocol similar to msnp needs to be defined first, but today's topic is how to design this system with high scalability. As this project has not conducted well-developed customer communication and demand analysis, there will certainly be many extensions in the future, and the communication protocols will surely become larger and larger, as a less diligent person, I certainly don't want to modify the program later, so this project is a good opportunity to practice object-oriented design.

First, define an interface to isolate the class:

Package org. bromon. Reflect;

Public interface operator

{

Public java. util. List Act (Java. util. List Params)

}

Based on the principle of the design pattern, we can write different classes for different functions. Each class inherits the operator interface. The client only needs to program the operator interface to avoid a lot of trouble. For example:

Package org. bromon. Reflect .*;

Public class success implements Operator

{

Public java. util. List Act (Java. util. List Params)

{

List result = new arraylist ();

Result. Add (new string ("operation successful "));

Return result;

}

}

We can also write many other classes, but there is a problem that the interface cannot be instantiated. We must manually control which class to instantiate. This is quite uncomfortable, if we can pass a parameter to the application, let ourselves choose to instantiate a class and execute its act method, then our work will be much easier.

Fortunately, I am using Java. Only Java provides such a reflection mechanism, or an introspection mechanism, to meet our unreasonable requirements. Compile a configuration file EMP. properties:

# Successful response

1000 = Success

# Sending common text messages to customers

2000 = Load

# The customer sends a common text message to the server

3000 = store

The key name in the file is the message header that the customer will send to me. If the customer sends 1000 to me, then I will execute the act Method of the success class. Similarly, if 2000 is sent to me, execute the act Method of the load class, so that the system fully complies with the open and closed principles. To add new functions, you do not need to modify the existing code, you only need to add the corresponding rules in the configuration file, write a new class, and implement the Act method. Even if I discard this project, it will be very scalable in the future. Such a system has excellent scalability and insertion ability.

The following example shows the function of dynamic loading. During execution, the program knows which class should be instantiated:

Package org. bromon. Reflect .*;

Import java. Lang. Reflect .*;

Public class testreflect

{

// Load the configuration file and query the class name corresponding to the Message Header

Private string loadprotocal (string header)

{

String result = NULL;

Try

{

Properties prop = new properties ();

Fileinputstream FCM = new fileinputstream ("EMP. properties ");

Prop. Load (FS );

Result = prop. getproperty (header );

FCM. Close ();

} Catch (exception E)

{

System. Out. println (E );

}

Return result;

}

// Respond to messages and import corresponding classes using reflection

Public String response (string header, list content)

{

String result =Null;

String S =Null;

Try

{

/*

* Import the property file EMP. properties to query the class name corresponding to the header.

* Matching classes are dynamically loaded using the reflection mechanism. All classes are isolated by the operator interface.

* You can extend the Protocol by modifying the attribute file and adding a new class (inheriting the msgoperator interface ).

*/

S = "org. bromon. Reflect." +This. Loadprotocal (header );

// Load the class

Class C = Class. forname (s );

// Create a class example

Operator Mo = (operator) C. newinstance ();

// Construct the parameter list

Class Params [] =NewClass [1];

Params [0] = Class. forname ("Java. util. List ");

// Query the act Method

Method M = C. getmethod ("act", Params );

Object ARGs [] =NewObject [1];

ARGs [0] = content;

// Call the method and obtain the returned result

Object returnobject = M. Invoke (Mo, argS );

}Catch(Exception E)

{

System. Out. println ("Handler-response:" + E );

}

ReturnResult;

}

Public static void main (string ARGs [])

{

Testreflect TR = new testreflect ();

Tr. Response (ARGs [0], "message content ");

}

}

Test: Java testreflect 1000

This program is programmed for operator. Therefore, without any modifications, you can directly provide the load and store classes to support parameter calls in versions 2000 and 3000.

With this internal saving mechanism, the interface function can be played to the extreme, and the design model can also reflect the power, not just for chatting after dinner.

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.