Using Java reflection to get the private variable value of a class __java

Source: Internet
Author: User
Tags reflection

From the principle of design, if the member variable of a class is designed to be private, then we cannot get the value of this private variable outside the class. The usual practice is to provide the get and set methods for this private variable. But if this class does not provide get and set methods, how do we obtain the private member variable for that class? For example, there is a class person:

Class person{
	Private String name = "Cross";
}

How do we not get the value of name in this class? Can be obtained by means of the Java reflection mechanism, note that this will be field.setaccessible (true) for the name of this field, so that we can access the private variable

Package com.withiter.test;

Import Java.lang.reflect.Field;

public class Reflecttest {public

	static void Main (string[] args) {
		try {
			class<?> obj = Class.forName (" Com.withiter.test.Person ");
			Field[] f = obj.getdeclaredfields ();
			for (Field field:f) {
				field.setaccessible (true);
				System.out.println (Field.getname () + ":" +field.get (Obj.newinstance ()));
			}
		catch (ClassNotFoundException e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		} catch ( IllegalArgumentException e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		} catch ( Illegalaccessexception e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		} catch ( Instantiationexception e) {
			//TODO auto-generated catch block
			e.printstacktrace ();

}}} Class person{
	Private String name = "Cross";
}



Related Article

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.