Dynamic call of functions in Java

Source: Internet
Author: User

//-------------------------------------
// Class argumentholder
// Used to encapsulate call parameters to implement variable-length parameters and
// Unified transmission of different types of parameters
// Member variables:
// Class [] Cl parameter type array
// Object [] ARGs parameter object Array
// Method:
// Getargumentclasses () returns an array of parameter types
// Getarguments () returns an array of parameter objects
// Setargument () Add a project to the parameter list
//
//---------------------------------------
Public class argumentholder {
Protected class [] Cl;
Protected object [] ARGs;
Protected int argc;
 
Argumentholder (){
Argc = 0;
CL = new class [0];
ARGs = new object [0];
}
Argumentholder (INT argc ){
This. argc = argc;
CL = new class [argc];
ARGs = new object [argc];
}
 
Public class [] getargumentclasses (){
Return Cl;
}
Public object [] getarguments (){
Return ARGs;
}
 
// The following 16 setargument
// Function implementation: Boolean, byte,
// Encapsulation of char, Int, short, long, float, and double.
// Invoker is supported
// Call the getclass in the dynacall method,
// Simple data type
// Convert to the corresponding object, such as Boolean to boolean
Public int setargument (Boolean B ){
Return this. setargument (argc, new Boolean (B ),
Boolean. type );
}
Public int setargument (INT argnum, Boolean B ){
Return this. setargument (argnum, new Boolean (B), Boolean. type );
}
Public int setargument (byte B ){
Return this. setargument (argc, new byte (B), byte. type );
}
 
Public int setargument (INT argnum, byte B ){
Return this. setargument (argnum, new byte (B), byte. type );
}
Public int setargument (char c ){
Return this. setargument (argc, new character (C), character. type );
}
Public int setargument (INT argnum, char c ){
Return this. setargument (argnum, new character (C), character. type );
}
Public int setargument (int I ){
Return this. setargument (argc, new INTEGER (I), integer. type );
}
Public int setargument (INT argnum, int I ){
Return this. setargument (argnum, new INTEGER (I), integer. type );
}
Public int setargument (short S ){
Return this. setargument (argc, new short (s), short. type );
}
Public int setargument (INT argnum, short S ){
Return this. setargument (argnum, new short (s), short. type );
}
Public int setargument (long l ){
Return this. setargument (argc, new long (L), long. type );
}
Public int setargument (INT argnum, long l ){
Return this. setargument (argnum, new long (L), long. type );
}
Public int setargument (float f ){
Return this. setargument (argc, new float (F), float. type );
}
Public int setargument (INT argnum, float f ){
Return this. setargument (argnum, new float (f ),
Float. type );
}
Public int setargument (double D ){
Return this. setargument (argc, new double (D), double. type );
}
Public int setargument (INT argnum, double D ){
Return this. setargument (argnum, new double (D), double. type );
}
 
// The following two setargument functions implement object encapsulation,
Public int setargument (Object OBJ ){
Return this. setargument (argc, OBJ,
OBJ. getclass ());
}
Public int setargument (INT argnum, object OBJ ){
Return this. setargument (argnum, OBJ,
OBJ. getclass ());
}
 
// The following setargument function is implemented as an object
// Encapsulate the provided parameters.
// The specific operation is: Increase the counter argc value,
// Add the corresponding content to Cl and ARGs
Public int setargument (INT argnum, object OBJ, Class C ){
If (argnum> = args. Length ){
Argc = argnum + 1;
Class [] clexpanded = new class [argc];
Object [] argsexpanded = new object [argc];
System. arraycopy (CL, 0, clexpanded,
0, Cl. Length );
System. arraycopy (ARGs, 0, argsexpanded,
0, argS. Length );
CL = clexpanded;
ARGs = argsexpanded;
}
ARGs [argnum] = OBJ;
Cl [argnum] = C;
Return argnum;
}
}
//
// ---- Give an example of invoker and argumentholder.
// Dynacalltest class should use the class invoker and argumentholder to implement the following functions: the internal capacity that the root user enters in the command line, determines the calling method dynamically. The process order can be input by the Union method:
//
// The add parameter is two integers, showing the sum of the two integers
// The Concat parameter is two strings and the value after the two strings are connected is displayed
// The HELP parameter is not set. The list of acceptable commands is displayed.
// The MINMAX parameter is a three-integer that displays the maximum and minimum values of the three parameters.
// Quit has no parameters and stops running.
// Rand has no parameters. A Random value is displayed.
//
// The program list is as follows:
Import java. Io. bufferedreader;
Import java. Io. ioexception;
Import java. Io. inputstreamreader;
Import java. Lang. Reflect. invocationtargetexception;
Import java. util. Random;
Import java. util. stringtokenizer;

Public class dynacalltest {
 
Random rand;
Bufferedreader consolein;
 
// Construct a function and initialize it.
Dynacalltest (){
Consolein = new bufferedreader
(New inputstreamreader (system. In ));
Rand = new random ();
}
// Read user input lines
String getcommandline () throws ioexception {
System. Out. Print ("> ");
System. Out. Flush ();
String CommandLine = lelein. Readline ();
If (CommandLine = NULL)
Return "quit ";
If (CommandLine. Length () = 0)
Return "quit ";
Else
Return CommandLine;
}
 
// Extract the command from the user input line,
// Format to: uppercase for the first character and lowercase for other characters
// Return the formatted command
String extractcommand (string CommandLine ){
Stringtokenizer T = new stringtokenizer (CommandLine );
String cmd = T. nexttoken (). tolowercase ();
Return cmd. substring (0, 1). touppercase ()
+ Cmd. substring (1 );
}
 
// Extract parameters from the user input line,
// Create argumentholder type object A to encapsulate all parameters
// An integer in the wrong format is treated as a string.
// Returns an argumentholder-type object, that is, the encapsulated parameter.
Argumentholder extractarguments (string cmd ){
Stringtokenizer T = new stringtokenizer (CMD );
Int tokencount = T. counttokens ();
Argumentholder A = new argumentholder ();
String token = T. nexttoken ();
While (T. hasmoretokens ()){
Token = T. nexttoken ();
Try {
Int I = integer. parseint (token );
A. setargument (I );
}
Catch (numberformatexception e ){
A. setargument (token );
}
}
Return;
}
 
// The following six functions starting with meth are implemented in this test.
// The specific processing process of valid commands.
// Function naming rules: Meth + formatted USER commands
Public String methadd (INT I1, int I2 ){
Return integer. tostring (I1) + "+" +
Integer. tostring (I2) + "=" + integer. tostring (I1 + I2 );
}
Public String methconcat (string S1, string S2 ){
Return "the concatenated string is" + S1 + S2;
}
Public String methhelp (){
Final string [] helpmessages =
{"Dynacalltest version 1.0 ",
"Valid commands are :",
"Add int1 int2 ",
"Concat string1 string 2 ",
"Help ",
"MINMAX int1 int2 int3 ",
"Quit ",
"RAND"
};
For (INT I = 0; I System. Out. println (helpmessages [I]);
Return "";
}
Public String methminmax (INT I1, int I2, int I3 ){
Return ("min =" +
Integer. tostring (Java. Lang. Math. Min
(Java. Lang. Math. Min (
I1, I2), I3) + ", max =" + integer. tostring (
Java. Lang. Math. Max (Java. Lang. Math. Max (I1, I2), I3 )));
}
Public String methquit (){
Return "quitting ";
}
Public String methrand (){
Return "the random number is"
+ Integer. tostring (RAND. nextint ());
}
 
// Process user input in the command line
// Call extractcommand to generate the method name corresponding to user input
// Call extractarguments to encapsulate user input parameters
// Call invoker. dynacall to implement command processing
String processcommand (string cmd ){
Try {
String meth = "meth" + extractcommand (CMD );
Argumentholder A = extractarguments (CMD );
Return (string) (invoker. dynacall (this, meth, ));
}
Catch (nosuchmethodexception e ){
Return "no method to process command" + cmd;
}
Catch (invocationtargetexception e ){
System. Out. println ("Trace :");
E. printstacktrace ();
Return "invocationtargetexception Processing Command" + cmd;
}
Catch (illegalaccessexception e ){
System. Out. println ("Trace :");
E. printstacktrace ();
Return "illegalaccessexception Processing Command" + cmd;
}
}
 
// Main function, call processcommand to implement program functions
Public static void main (string ARGs []) {
Boolean Allok = true;
String line;

Dynacalltest myclient = new dynacalltest ();

System. Out. println ("dynacalltest version 1.0 ");
System. Out. println ("Enter command at the prompt ");
System. Out. println ("type help for help ");
While (Allok ){
Try {
Line = myclient. getcommandline ();
If (line = NULL)
Allok = false;
Else {
System. Out. println (myclient. processcommand (line ));
If (line. substring (0, 1). touppercase (). Equals ("Q "))
Allok = false;
}
}
Catch (ioexception e ){
E. printstacktrace ();
Allok = false;
}
}
System. Exit (0 );
}
}

//--------------------------------------
// Class invoker
// Implement dynamic function call
// Method:
// Dynacall
// Object C: The object where the function (method) is to be called
// String M name of the method to be called
// Parameters passed by argumentholder A to the called Method
//-----------------------------------------
Import java. Lang. Reflect. invocationtargetexception;
Import java. Lang. Reflect. method;
Public class invoker {
Static object dynacall (Object C, string m,
Argumentholder A) throws nosuchmethodexception, invocationtargetexception, illegalaccessexception {
 
// JAVA supports method name overloading.
// (More than one function with the same name appears in the same class ),
// Therefore, the getmethod method uses two parameters:
// Method name and array form in string form
// List of call parameter classes. The returned value is an object of the class method,
// This object and the object to be
// Associate the called Method
Method meth = C. getclass (). getmethod (M, A. getargumentclasses ());
 
// Call the expected method dynamically through the invoke method of the class method object
Return (meth. Invoke (C, A. getarguments ()));
}
}

 

 

Source: http://www.cn-java.com/www1? Action-viewnews-itemid-2317

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.