Java reflection, know the class name to create a class, you can also set the value of the private property, java private

Source: Internet
Author: User

Java reflection, know the class name to create a class, you can also set the value of the private property, java private

I just learned reflection, and I feel that reflection is powerful. So I want to write a blog to record my learning achievements.

Use reflection to create objects.

Class c1 = Class. forName ("test. Person"); // create a Class by Class name. Here test. person is just a Class name ,. The person class code is at the bottom of // This article/*** Case 1: Call the construction method without parameters to create an object */Person p = c1.newInstance (); // In this case, the/*** scenario 2 is created: Call the construction method with parameters */Constructor cs = c1.getConstructor (String. class, int. class); // The parameter type of the constructor is written in the brackets, that is, it is added later. class is ready for Person p = (Person) cs. newInstance ("Zhang San", 22); // call the constructor to generate an objectView Code

Use reflection to set Private attributes

Try {Class clazz = Class. forName ("testPerson"); Person p = (Person) clazz. newInstance (); Field f1 = clazz. getDeclaredField ("name"); f1.setAccessible (true); // sets whether private attributes f1.set (p, "wfadf") can be operated; System. out. println (f1.get (p);} catch (Exception e) {// TODO Auto-generated catch block throw new RuntimeException (e );}

Person code

package test;public class Person {    private String name;    private int age;        public Person() {            }    public Person(String name, int age) {            this.name = name;        this.age = age;    }    public String getName() {        return name;    }/*    public void setName(String name) {        this.name = name;    }*/    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

 

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.