Java method Reflection is assigned to a property

Source: Internet
Author: User

A problem that you often encounter is that you need to set the property value for a Pojo class, but sometimes it's cumbersome to call over and over again, and you can take advantage of the Java reflection mechanism.

Pojo class:

public class Dotstat implements Serializable {
Private Integer ID;
Private String model;
Private String Adccompany;
Private String ossdk;
Private String av;
Private String phone;
Private Integer Enterpriseid;
Private String Citypinyin;
Private Integer Industryid;
Private Date statdate;

--------------------------------------------

Get and Set method

}

Using the method of reflection, we need to assign a value to the id attribute of the Dotstat class, which is the property name, the value to assign, and the Dotstat object

private void Setattributevalue2dotstat (String attributename, Integer times, Dotstat dot) {

      //capitalize the first letter of the property name.

String setattributemethodname = "Set" + character.touppercase (Attributename.charat (0)) + attributename.substring (1);
try {
Method Setattributemethod = DotStat.class.getDeclaredMethod (Setattributemethodname,integer.class);
Setattributemethod.invoke (Dot,st.gettimes ());
catch (SecurityException e) {
catch (Nosuchmethodexception e) {
catch (IllegalArgumentException e) {
catch (Illegalaccessexception e) {
catch (InvocationTargetException e) {
}
}

This is to use the reflection mechanism to assign a value to a property

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.