Use reflection
Public class reflecttest {
Public static void main (string [] ARGs) throws exception {
Class clazz = user. Class;
Object OBJ = create (clazz );
System. Out. println (OBJ );
Invoke1 (OBJ, "showname ");
System. Out. println ("------------------");
Field (clazz );
}
Static object create (class clazz) throws exception {
Constructor con = clazz. getconstructor (string. Class );
Object OBJ = con. newinstance ("test name ");
Return OBJ;
}
Static void invoke1 (Object OBJ, string methodname) throws exception {
Method [] MS = obj. getclass (). getdeclaredmethods ();
MS = obj. getclass (). getmethods ();
For (method M: MS ){
// System. Out. println (M. getname ());
If (methodname. Equals (M. getname ())){
M. Invoke (OBJ, null );
}
}
Method M = obj. getclass (). getmethod (methodname, null );
M. Invoke (OBJ, null );
}
Static void field (class clazz) throws exception {
Field [] FS = clazz. getdeclaredfields ();
// FS = clazz. getfields ();
For (field F: FS ){
System. Out. println (F. getname ());
}
}
Static void annon (class clazz) throws exception {
Annotation [] as = clazz. getannotations ();
}
}
------------------------------------------------------------------
Public class ormtest {
Public static void main (string [] ARGs ){
User user = (User) GetObject (
"Select ID as ID, name as name, birthday as birthday, money as money from user where id = 1 ",
User. Class );
System. Out. println (User );
}
Static object GetObject (string SQL, class clazz ){
Connection conn = NULL;
Preparedstatement PS = NULL;
Resultset rs = NULL;
Object object = NULL;
Try {
// Establish a connection
// Conn = jdbcutils. getconnection ();
Conn = jdbcutilssing. getinstance (). getconnection (); // Singleton
PS = conn. preparestatement (SQL );
Rs = ps.exe cutequery ();
Resultsetmetadata rsmd = Rs. getmetadata ();
Int COUNT = rsmd. getcolumncount ();
String [] colnames = new string [count];
For (INT I = 1; I <= count; I ++ ){
Colnames [I-1] = rsmd. getcolumnlabel (I); // If an alias is set, the name is the same as the label if no alias is set.
}
Object = clazz. newinstance ();
Method [] MS = object. getclass (). getmethods ();
While (Rs. Next ()){
For (INT I = 0; I <colnames. length; I ++ ){
String colname = colnames [I];
String methodname = "set" + colname;
For (method M: MS ){
If (methodname. Equals (M. getname ())){
M. Invoke (object, Rs. GetObject (colname ));
}
}
}
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Jdbcutils. Free (RS, PS, Conn );
}
Return object;
}
}