Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

forName("setMethod")

Status
Not open for further replies.

adm1122

Programmer
Jul 11, 2000
3
AU
Is is possible to create a known class and then use a string
as the method name? similar to this sample. I want to use this where the method to be invoked will be read in as a string from an input file.

AnyClass c = new AnyClass();
c.("setMethod")

thanks.
 
If "yourClass" is a Class object represent your class, "yourInst" is an instance of your class, and strMethod is a string containing the name of the method to be invoked, then there are 2 approaches, depending on whether all the methods have unique names or whether at least two have the same names and different signatures.

import java.lang.reflect;

1. All method names unique

Method[] yourMethods = yourClass.getDeclaredMethods();
for ( int i = 0; i < yourMethods.length; i++ ) {
if ( strMethod.equals( yourMethods[ i ].toString() ) ) {
yourInst.invoke( yourMethods[ i ], args );
//etc
}
}

2. Some method names not unique

Method yourMethod = yourClass.getDeclaredMethod( strMethod, parameterTypes );
yourInst.invoke( yourMethod, args );

where args is an array of Objects containing the arguments
and parameterTypes is an array of Classes representing the method's signature

more info can be found in the J2SE API documentation for java.lang Class and java.lang.reflect Method
 
Thanks. I'll give it a try in the morning
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top