Java Reference
In-Depth Information
public char java.lang.String.charAt(int)
public int java.lang.String.compareTo(java.lang.Object)
public int java.lang.String.compareTo(java.lang.String)
You can see that this could be extended (almost literally) to write a BeanMethods class that
would list only the set/get methods defined in a JavaBean (see Preparing a Class as a
JavaBean ) .
Alternatively, you can find a particular method and invoke it, or find a particular field and
refer to its value. Let's start by finding a given field, because that's the easiest. Example 23-2
is code that, given an Object and the name of a field, finds the field (gets a Field object)
and then retrieves and prints the value of that Field as an int .
Example 23-2. FindField.java
public
public class
class FindField
FindField {
public
public static
static void
void main ( String [] unused )
throws
throws NoSuchFieldException , IllegalAccessException {
// Create instance of FindField
FindField gf = new
new FindField ();
// Create instance of target class (YearHolder defined below).
Object o = new
new YearHolder ();
// Use gf to extract a field from o.
System . out . println ( "The value of 'currentYear' is: " +
gf . intFieldValue ( o , "currentYear" ));
}
int
int intFieldValue ( Object o , String name )
throws
throws NoSuchFieldException , IllegalAccessException {
Class <?> c = o . getClass ();
Field fld = c . getField ( name );
int
int value = fld . getInt ( o );
return
return value ;
}
}
/** This is just a class that we want to get a field from */
class
class YearHolder
YearHolder {
/** Just a field that is used to show getting a field's value. */
public
public int
int currentYear = Calendar . getInstance (). get ( Calendar . YEAR );
}
Search WWH ::




Custom Search