Java Dynamic call class Method Instance

Source: Internet
Author: User
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

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.