Java reflection to set the value method

Source: Internet
Author: User
Tags object object reflection
Package Com.newegg.frontservice.controller;


Import Java.beans.PropertyDescriptor;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;


public class Test2 {

public static void Main (string[] args)
Throws Exception {
Class Clazz = Class.forName ("COM.NEWEGG.FRONTSERVICE.CONTROLLER.ABC");//This is the full name. If you have a bag, add the name.
Object obj = clazz.newinstance ();
field[] fields = Clazz.getdeclaredfields ();
Write Data
for (Field f:fields) {
PropertyDescriptor PD = new PropertyDescriptor (F.getname (), clazz);
Method WM = Pd.getwritemethod ();//Get Write methods
Wm.invoke (obj, "");//Because you know it is an int type of property, so pass an int. In fact, we need to judge his parameter type.
}
Reading data
for (Field f:fields) {
PropertyDescriptor PD = new PropertyDescriptor (F.getname (), clazz);
Method WM = Pd.getwritemethod ();
Method RM = Pd.getreadmethod ();//Get Read
String num = (string) rm.invoke (obj);//Because you know it is an int type of property, so convert to integer. You can also print directly without converting
Object object = Rm.invoke (obj);
if (Object!=null && object instanceof String && object.equals ("")) {
Wm.invoke (obj, null);
}
SYSTEM.OUT.PRINTLN (num);
}

for (Field f:fields) {
PropertyDescriptor PD = new PropertyDescriptor (F.getname (), clazz);
Method RM = Pd.getreadmethod ();//Get Read
String num = (string) rm.invoke (obj);//Because you know it is an int type of property, so convert to integer. You can also print directly without converting
Object object = Rm.invoke (obj);

SYSTEM.OUT.PRINTLN (num);
}

}
}
Class abc{
Private String AB;
Private String cd;
Public String Getab () {
return AB;
}
public void Setab (String ab) {
This.ab = AB;
}
Public String Getcd () {
return CD;
}
public void Setcd (String CD) {
THIS.CD = CD;
}

}

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.