Idea Analysis:
First, use Class to obtain a class object representing the String class, and then use the getDeclaredFields() method of the Class class to obtain all member variables and assign them to a Field-type array, that is, all fields of the String class are obtained.
Use foreach() to loop through all fields, use the getName() method of the Field class to get the name of the member variable. If the name of the field is hash, try to use the getInt(Object obj) method of the Field class to get the type int in the specified object The value of this member variable.
Catch the IllegalArgumentException and the IllegalAccessException exception in turn.
The code is as follows:
The code copy is as follows:
import java.lang.reflect.Field;
public class ExceptionTest {
public static void main(String[] args) {
Class<?> clazz = String.class; //Get the class object representing the String class
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) { //Transfuse all fields
System.out.println(field);
if (field.getName().equals("hash")) { //If the domain name is hash
try {
System.out.println(field.getInt("hash")); // Output the hash value
} catch (IllegalArgumentException e) { //Catch IllegalArgumentException exception
System.out.println(e);
} catch (IllegalAccessException e) { //Catch IllegalAccessException exception
System.out.println(e);
}
}
}
}
}