Thinking Analysis:
First you use class to get a class object that represents the string class, and then you use the Class class's Getdeclaredfields () method to get all the member variables and assign them to a field array, which gets all the fields of the string class.
Use a foreach () loop to iterate through all the fields, using the GetName () method of the field class to get the name of the member variable, and if the domain name is hash, try to use the field class's Getint (Object obj) method to obtain the value of the member variable of type int in the specified object.
Catch illegalargumentexception exceptions and illegalaccessexception exceptions sequentially.
The code is as follows:
Copy Code code as follows:
Import Java.lang.reflect.Field;
public class Exceptiontest {
public static void Main (string[] args) {
class<?> clazz = String.class; Gets the class object that represents the String class
field[] fields = Clazz.getdeclaredfields ();
for (field Field:fields) {//Traverse all fields
System.out.println (field);
if (Field.getname (). Equals ("hash")) {//If the domain name is hash
try {
System.out.println (Field.getint ("hash")); Value of output hash
catch (IllegalArgumentException e) {//Catch IllegalArgumentException exception
System.out.println (e);
catch (Illegalaccessexception e) {//Catch Illegalaccessexception exception
System.out.println (e);
}
}
}
}
}