Obtain class attribute fields and call class methods through reflection
Public class modelclasshelper {
Public static hashmap <string, class> Init (string classpath)
{
Try {
// "Com. geocompass. model. ststbprpmodel"
Hashmap <string, class> fieldhashmap = new hashmap <string, class> ();
Class CLS = Class. forname (classpath); // com. geocompass. model. ststbprpmodel
Field [] fieldlist = Cls. getdeclaredfields ();
For (INT I = 0; I <fieldlist. length; I ++ ){
Field identifier = fieldlist [I];
Fieldhashmap. Put (response. getname (), response. GetType ());
// System. Out. println ("name =" + response. getname ());
// System. Out. println ("Decl class =" + response. getdeclaringclass ());
// System. Out. println ("type =" + response. GetType ());
// System. Out. println ("-----");
}
Return fieldhashmap;
} Catch (classnotfoundexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return NULL;
} Public static string gettablename (string classpath)
{
Try {
Class CLS = Class. forname (classpath );
Method test = Cls. getdeclaredmethod ("gettablename ");
Object invoke =Test. Invoke (CLS. newinstance ());
Return invoke. tostring ();
// Cls. assubclass (tabmodel. Class );
} Catch (classnotfoundexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (securityexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (nosuchmethodexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (illegalargumentexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (illegalaccessexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (invocationtargetexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (instantiationexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return "";
}}
Dynamic acquisition of any Java instance Using Reflection TechnologyAttribute Value
Package org. Apache. easframework. Core. entity. impl;
Import java. Lang. Reflect. field;
Public class testentity {
Private string code;
Private string name;
Public void setcode (string code)
{
This. Code = code;
}
Public String getcode ()
{
Return this. Code;
}
Public void setname (string name)
{
This. Name = Name;
}
Public String getname ()
{
Return this. Name;
}
Public static void main (string [] ARGs) throws securityexception, classnotfoundexception, illegalargumentexception, illegalaccessexception
{
Testentity OBJ = new testentity ();
OBJ. setname ("name value ");
OBJ. setcode ("code value ");
Field [] FDS = Class. forname
("Org. Apache. easframework. Core. entity. impl. testentity"). getdeclaredfields ();
System. Out. println (FDS. Length );
For (INT I = 0; I <FDS. length; I ++)
{
System. Out. println (FDS [I]. Get (OBJ ));
}
}
}
Reprinted from:
Http://blog.csdn.net/wpcxyking/article/details/6139549