Finding and Using Methods and Fields
Problem
You need more to find arbitrary method or field names in arbitrary classes.
Solution
Use the reflection package
java.lang.reflect
.
Discussion
If you just wanted to find fields
and
methods in one particular class, you wouldn’t need this; you
could simply create an instance of the class using
new and refer to its fields and methods directly.
This allows you to find methods and fields in any class, even classes
that have not yet been written! Given a class object created as in
Section 25.2, you can obtain a list of constructors,
a list of methods, or a list of fields. The method
getMethods( )
lists the methods available for a given class as an array of
Method objects. Since constructor methods are
treated specially by Java, there is also a getConstructors( )
method,
which returns an array of Constructor objects.
Even though “class” is in the package
java.lang, the Constructor,
Method, and Field objects it
returns
are in
java.lang.reflect, so you need an import of this
package. The ListMethods class (Example 25-1) shows how to do this.
Example 25-1. ListMethods.java
import java.lang.reflect.*; /** * List the Constructors and methods */ public class ListMethods { public static void main(String[] argv) throws ClassNotFoundException { if (argv.length == 0) { System.err.println("Usage: ListMethods className"); return; } Class c = Class.forName(argv[0]); Constructor[] cons = c.getConstructors( ); printList("Constructors", cons); Method[] meths ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access