Java implementation Illegal Access exception sample _java

Source: Internet
Author: User

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);
}
}
}
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.