Use reflection to set the field value of the object

Source: Internet
Author: User

Package COM. sadhu; import Java. util. *; import Java. lang. reflect. *;/***/public class sample {public static void main (string [] ARGs) throws exception {class Cl = Class. forname ("com. sadhu. reflecttest "); object RT = Cl. newinstance (); // create an object field [] field = Cl. getdeclaredfields (); For (field item: Field) {item. setaccessible (true); // if the value is true, it indicates that the reflected object should cancel the Java language access check during use. If the value is false, it indicates that the reflected object should perform Java access checks. If (item. getType () = string. class) {item. set (RT, "Zhang San");} If (item. getType () = int. class) {item. set (RT, 10);} system. out. println (item. get (RT); // output the value of the current field in the object }}} class reflecttest {private string name; private int age; Public void setname (string aname) {This. name = aname;} Public String getname () {return this. name;} public void setage (INT Aage) {This. age = Aage;} public int getage () {re Turn this. Age;} public reflecttest () {system. Out. println ("Call the parameter-free constructor! ") ;}}/** Output result: No parameter constructor is called! John 10 */


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.