Java Reference
In-Depth Information
C:\javasrc\reflect>
java ClassKeyword
Trying the ClassName.class keyword:
Object class: class java.lang.Object
String class: class java.lang.String
String[] class: class [Ljava.lang.String;
Calendar class: class java.util.Calendar
Current class: class ClassKeyword
Class for int: int
Trying the instance.getClass( ) method:
class java.lang.String
class java.util.GregorianCalendar
C:\javasrc\reflect>
Nothing fancy, but as you can see, you can get the
Class
object for almost anything known
at compile time, whether it's part of a package or not.
Finding and Using Methods and Fields
Problem
You need 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
recipe; you could simply create an instance of the class using
new
and refer to its fields and
methods directly. But 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
Getting a Class Descriptor
,
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.
Similarly,
getFields()
returns a list of
Field
objects. Because constructor methods are
treated specially by Java, there is also a
getConstructors()
method, which returns an array