I. Overview
I have already introduced some basic knowledge about Java. Lang. Reflect. This section describes how to program and test an instance.
Two classes in two packages are used here. The list of packages and files in the package is as follows:
Testclass package: This package contains a compiled class class1, which has only one method to add.
Dyn_callmethod package: This package contains a compiled class callclass, which contains the main function main () used as the main function (). This function dynamically calls the Add function of the class1 class in the testclass package.
Ii. Source Code
1. class1 class of the testclass package:
Package testclass;
Public class class1 {
Public class1 (){
}
Public int add (int A, int B ){
Return A + B;
}
}
2. callclass class in the dyn_callmethod package:
Package dyn_callmethod;
Import java. Lang. Reflect .*;
Import testclass .*;
Public class callclass {
Public callclass (){
}
Public static void main (string ARGs []) {
Try {
Class CLS = Class. forname ("testclass. class1 ");
System. Out. println ("load the target class ");
Class partypes [] = new class [2];
Partypes [0] = integer. type;
Partypes [1] = integer. type;
Method meth = Cls. getmethod ("add", partypes );
System. Out. println ("Get the method of the class ");
Testclass. class1 methobj = new testclass. class1 ();
Object Arglist [] = new object [2];
Arglist [0] = new INTEGER (37 );
Arglist [1] = new INTEGER (47 );
Object retobj = meth. Invoke (methobj, Arglist );
Integer retval = (integer) retobj;
System. Out. println (retval. intvalue ());
}
Catch (exception e ){
System. Err. println (E );
}
}
}
3. output results after running:
Load the target class
Get the method of the class
84