Introduction and use of Beanutils

Source: Internet
Author: User
Tags dateformat
Introduction and use of Beanutils

Beanutils Introduction and its use overview guide packages use the Beanutils tool when using a custom data type an example of the conditions you must have

Overview

The Beanutils tool, written by the Apache Software Fund, is available to us, and the main solution is to encapsulate the object's attribute data into the object. Throughout the Java EE programming process, we often read the appropriate data from a variety of configuration files, and it is important to understand that the data read from the configuration file is string, but it is clear that our application is not only a string of data types, for example: basic data types (int, Double, char, float, and so on), and custom data types (reference data types), then one of the problems we have to face is what to do if the string type is converted to a variety of specific data types. There are two ways for us to use:

First you judge the data type you want, and then call the appropriate method on the string type to convert it to the type we want

Using the Beanutils tool

For the two methods mentioned above, we analyze the first problem is too cumbersome, each time a large number of type conversion, the Apache Software Foundation provides us with a second method, using its beanutils tools, Specifically, only to know that two of these methods can achieve the type of conversion, very simple, reduce the difficulty of programming. Guide Bag

Obviously, if you want to use a tool that someone else developed must import its jar package into your program, but Beanutils Baoqun is dependent on another package, the name of the jar package is shown below, with the version number not necessarily the same as the one I used. Commons-beanutils-1.9.2.jar Download Address: http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi Commons-logging.jar Download Address: https://commons.apache.org/proper/commons-logging/download_logging.cgi

Please download the latest version, and the corresponding jar package imported into the program, the specific way to import the jar package here is no introduction, this is the most basic knowledge, as long as you are engaged in Java EE Project development, almost every day will encounter a variety of different jar package import. before you start writing specific code, import source into your program, or you will not be able to generate the correct overloaded function, just use the bar attach Source, import the jar package (imported in the same way as an external file, and do not import with an external folder). Use

The Beanutils tool uses only a few of the following methods, one of which is typically the use of anonymous inner classes. Beanutils.setproperty (bean, name, value); Where the bean refers to the object you are going to set, name refers to the property that will be set (written as "property name"), value (the string value read from the configuration file) Beanutils. Copyproperties (bean, name, value) is exactly the same as the method above. You use this method to implement transformations when you need to convert string data to a reference data type (a custom data type) by using either Convertutils.register (Converter Converter, ...). Beanutils.populate (Bean,map), where the key in the MAP must be the same as the property name in the target object, otherwise the copy cannot be implemented. Beanutils.copyproperties (Newobject,oldobject), to implement the copy of the object custom data types must be available when using the Beanutils tool

Custom data types when using the Beanutils tool, you must have getter and setter methods, because the Beanutils tool itself is an introspective implementation, so it is also converted with the help of the underlying getter and setter methods. An example

objects that you want to encapsulate as JavaBean

Package com.jpzhutech.beanutils;

Import Java.util.Date;

Import Javax.xml.crypto.Data;
    public class EMP {private int id;
    private String name;
        public Emp (int ID, String name, double salary, date date) {super ();
        This.id = ID;
        THIS.name = name;
        This.salary = salary;
    This.date = date;
    private double salary;


    private date date;
    Public Date getDate () {return date;
    public void setdate (date date) {this.date = date;
    Public Emp () {} public int getId () {return id;
    The public void setId (int id) {this.id = ID;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public double getsalary () {return salary;
    The public void Setsalary (double salary) {this.salary = salary; @Override public String toString () {//TODO Auto-generAted method Stub return "No.:" +this.id+ "Name:" +this.name+ "Salary:" +this.salary+ "Birthday: +date;
 }

}

Convert using the Beanutils component

/** * Beanutils Tool use * Function: Beanutils is mainly used to encapsulate properties of objects into objects * beanutils Benefits: * Beanutils When setting property values, if the attribute is the base data type, then Beanutils will automatically help us Conversion of data types, and * Beanutils setting properties is also dependent on the underlying getter and setter methods * * If you set a property value that is another reference data type, you must register a type converter to implement the automatic conversion */Package C

Om.jpzhutech.beanutils;
Import java.lang.reflect.InvocationTargetException;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;

Import Java.util.Date;

Import Javax.xml.crypto.Data;
Import Org.apache.commons.beanutils.BeanUtils;
Import Org.apache.commons.beanutils.ConvertUtils;
Import Org.apache.commons.beanutils.Converter;

Import Org.apache.commons.beanutils.locale.converters.DateLocaleConverter; public class Testbeanutils {public static void main (string[] args) throws Illegalaccessexception, Invocationtargetexc
        eption {//The data read from a file is a string of data, or the data submitted by the form is also string data///In Java EE programming, we get the data we want through the configuration file or directly from the file to obtain the data So there's a problem, when we need an int, and the data we read is string, then we have to determine what data type we need to be in the first place, and then do a forced type conversionit. The answer is no, we use the Apache Software Foundation to provide the Beanutils tools//No need to control what kind of data type, only the beanutils of the SetProperties method, the method has three parameters, the three parameters set will be
            /implement automatic data type conversion/*convertutils.register (new Converter () {//Custom date type converter @Override

                public object Convert (Class type, Object value) {//type: Data type value that is currently required to be converted: value of current parameter//target: Convert string to date

                if (type!= date.class) return null; if (value = NULL | |
                "". Equals (Value.tostring (). Trim ()) {return null;
                } SimpleDateFormat DateFormat = new SimpleDateFormat ("YYYY year mm month DD Day");
                Date date = null;
                try {date = Dateformat.parse ((String) value);
                catch (ParseException e) {throw new RuntimeException (e);
            } return date;  }}, Date.class);
 Date.class represents the reference type to be converted, and the date type is not the base data type, so a converter is required for the corresponding conversion, and the same functionality belongs to the Beanutils       *///Use the Date Converter tool class Convertutils.register (new Datelocaleconverter (), date.class);  Not flexible, achieve your own best String id = "110";
        We use this three string attribute to represent the data read from the configuration file, which reads String name = "Zhu Junpeng" directly from the properties file in the actual programming process;
String salary = "1000"; String birthday = "January 30, 2015";  If the converter provided in the tool must conform to a certain format, the conversion String birthday = "2015-01-30" cannot be implemented like this format;  The format can be implemented using the converter class provided by the tool to convert the string correctly, emp p = new EMP (); After reading to the data, set the properties of the object, use the Beanutils tool to avoid coercion of type conversions, but each property in the EMP class has getter and setter methods//Because the Beanutils  It is actually a encapsulation of introspection to make it more useful, so its underlying or dependent getter and Setter methods Beanutils.setproperty (p, "id", id);   where p represents the object Beanutils.setproperty (p, "name", name) to be set; The middle parameter represents the property to be set Beanutils.setproperty (p, "salary", salary);

        The third parameter represents the value of the second property Beanutils.setproperty (p, "date", birthday);
    SYSTEM.OUT.PRINTLN (P);
 }
}

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.