Add Pojotoxmlhelper to convert Pojo object to XML file--redirect using standard output

Source: Internet
Author: User
Tags reflection stringbuffer

Because it is assumed that the object stored in each table is actually a Pojo object, the structure of this table is the Pojo class, and the purpose of adding this function is to use it as a convenient data transfer, and each Pojo class can be saved as the full name of the Class + ". xml" suffix form.

Also want to use dom4j, but mainly to learn the Java Foundation, do not want to introduce too many external packages, try to use the features of the JDK.

The simplest is actually the implementation of the output redirection XML write.

Package cn.iamsese.prj.db.helper;
Import java.io.FileNotFoundException;
Import Java.io.PrintStream;

Import Java.lang.reflect.Field; /** * Java Pojo class to XML document Helper * Cn.iamsese.prj.db.helper * PM 03:11:34 * @author Vb2005xu [Java Rookie] */public class Pojot Oxmlhelper {private Pojotoxmlhelper () {}/** pojotoxmlhelper static object */private static Pojotoxmlhelper Defaultpojotoxml
	Helper; /** * Returns a singleton instance of the Pojotoxmlhelper class * @return Pojotoxmlhelper */public static synchronized Pojotoxmlhelper Getdefault
		Pojotoxmlhelper () {if (Defaultpojotoxmlhelper = = null) return new Pojotoxmlhelper ();
	return defaultpojotoxmlhelper; }/** * @param args */public static void main (string[] args) {userextendinfotest testUser = new Userextendi
		Nfotest ();
		Testuser.setmobilephone ("1234");
		Pojotoxmlhelper.getdefaultpojotoxmlhelper (). Tranlate (TestUser);

	Pojotoxmlhelper.getdefaultpojotoxmlhelper (). Tranlate (New cn.iamsese.prj.db.core.table.USER_Table ()); }/** * Conversion operation Implementation *@param obj */public void tranlate (Object obj) {String fileName = myreflectionhelper.getclassname (obj) + ". xml";
		PrintStream pout = null;
		try {pout = new PrintStream (fileName);
			} catch (FileNotFoundException e) {//log--not yet implemented SYSTEM.OUT.PRINTLN ("Cannot create a file stream");
		E.printstacktrace ();
		}//redirect The default standard I/O system.setout (pout);
		System.out.println ("<?xml version= ' 1.0 ' encoding= ' UTF-8 '?>");
		System.out.println ("<properties>");
		field[] Fieldarray = Obj.getclass (). Getdeclaredfields ();   
            for (Field field:fieldarray) {String name = Field.getname ();   
            Capitalize the first letter name = name.substring (0, 1). toUpperCase () +name.substring (1);
            Disables Java access check to allow access to the private decorated property variable field.setaccessible (true);
            Object text = Myreflectionhelper.getfieldvalue (obj, field);
        System.out.println ("<" +name+ ">" + text + "</" +name+ ">"); } System.out.println ("</propeRties> ");
		if (pout! = null) {pout.close ();   
       
    }}} class Userextendinfotest {private String userName;   
       
    Private String Mobilephone;   
    Public String GetUserName () {return userName;   
    } public void Setusername (String userName) {this.username = UserName;   
    } public String Getmobilephone () {return mobilephone;   
    } public void Setmobilephone (String mobilephone) {this.mobilephone = Mobilephone;  }   
}

The custom reflection class Myreflectionhelper that

  relies on is self-defined, and is not yet functional enough.

Package cn.iamsese.prj.db.helper;

Import Java.lang.reflect.Field; /** * Custom Reflection Tool Encapsulation Class Cn.iamsese.prj.db.helper * Author:vb2005xu [Java Rookie] */public class Myreflectionhelper {/** * Returns the class name of the specified object [including package name] * Supports incoming parameters such as Jdkloggerhelper.class * @param o * @return className */public static String Getcla
		Ssname (Object o) {if (o = = null) throw new NullPointerException ("Incoming object is null" + O);
		String className = O.getclass (). GetName ();
	return className; }/*--------related to class properties [now defined methods can only output properties of the class itself, not inherited properties]---------**//** * Returns the specified field of the specified object * * @param owner * @
		Param fieldName * @return field */public static field GetField (Object owner, String fieldName) {field F = null;
		try {f = owner.getclass (). Getdeclaredfield (FieldName);
		} catch (SecurityException e) {e.printstacktrace ();
		} catch (Nosuchfieldexception e) {e.printstacktrace ();
	} return F; }/** * Sets the value of the specified field for the specified object * @param owner * @param tf * @param value */public Static void SetField (object owner, Field tf, object value) {try {tf.set (owner, value);
		} catch (IllegalArgumentException e) {e.printstacktrace ();
		} catch (Illegalaccessexception e) {e.printstacktrace (); }}/** * Sets the value of the specified field for the specified object * @param owner * @param fieldName * @param value */public static void SetField (OBJ
		ECT owner, String fieldName, Object value) {Field f = GetField (owner, FieldName); SetField (owner, F, value);//Call the upper one another polymorphic form of this function}/** * Returns the value of the specified field for the specified object * @param owner * @param TF * @return OBJ
		ECT */public static object GetFieldValue (object owner, Field tf) {object v = null;
		try {v = tf.get (owner);
		} catch (IllegalArgumentException e) {e.printstacktrace ();
		} catch (Illegalaccessexception e) {e.printstacktrace ();
	} return v; /** * Returns the value of the specified field for the specified object * @param owner * @param fieldName * @return Object */public static object GetFieldValue (Object owner, String fieldName) {Field F = GetField (owner,FieldName); Return GetFieldValue (owner, F);//Call the upper one another polymorphic form of this function}/** * command line outputs the specified object, the value of the specified property * @param owner * @param f */PU
	Blic static void Printfieldvalue (Object owner, Field f) {System.out.println (GetFieldValue (owner, F)); The/** * command line outputs the specified object, specifying the value of the property * @param owner * @param fieldName */public static void Printfieldvalue (object owner, S
	Tring fieldName) {System.out.println (GetFieldValue (owner, fieldName));
		} public static void Printfieldinfo (Object owner, Field f) {StringBuffer sbuf = new StringBuffer ();
		Sbuf.append ("* * Current field information [Start]**\n");
		Sbuf.append ("Field name:" + f.getname ());
		Sbuf.append ("\ n");
		Sbuf.append ("Field type:" + F.gettype (). GetName ());
		Sbuf.append ("\ n");
		Sbuf.append ("Field value:" + getfieldvalue (owner, F));
		Sbuf.append ("\ n");

		Sbuf.append ("* * current field information [end]**\n");
	System.out.println (Sbuf.tostring ());
		} public static void Printfieldinfo (Object owner, String fieldName) {Field f = GetField (owner, FieldName); PrintfiEldinfo (owner, F); } public static void Printobjectfieldsinfo (Object owner) {System.out.println ("+++++" + owner.getclass (). GetName () + "
		++++ start \ n ");
		field[] fields = Owner.getclass (). Getdeclaredfields ();
		for (field Field:fields) {Printfieldinfo (owner, field);
	} System.out.println ("+++++" + owner.getclass (). GetName () + "++++ End");
	The public String toString () {return ' Custom reflection tool encapsulates class ';
 }
}

User_table.java this file, see the previous article in this series for an attachment pojotoxmlhelper running results. RAR (438 Bytes) Download number of times: 37

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.