Java dynamic call class method instance

xiaoxiao2021-03-06  41

One. Overview There are some basic knowledge about java.lang.Reflect. * In the previous section. Here is actually programmed by an example provided above and tested. Two classes in two packages are used here, respectively. The list of files used in the bags and packets is as follows: TestClass Package: This package contains a compiled class class1, which has only one method Add. Dyn_CallMethod Package: This package contains a compiled class CallClass, which contains the main function main () as the Motor. This function will realize the ADD function of the Class1 class in the TestClass package dynamically. two. Source code 1. Class1 Class of TestClass Package: Package TestClass; Public Class Class1 {Public Class1 () {} public int Add (int A, int b) {RETURN A B;}} 2. dyn_callmethod package CallClass classes: 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; class partypes [] = new class [2]; partypes [0] = integer.type; partypes [1] = Integer.Type; Method Meth = CLS.GETMETHOD ("Add", Partypes); System.Out.Println; 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 = (integer) Retobj; System .out.println (RetVal.intValue ());} catch (exception e) {system.err.println (e);}}} 3. Output results: loading the target classget the method of the class84

转载请注明原文地址:https://www.9cbs.com/read-68066.html

New Post(0)