Java Reflection Tool Class

Source: Internet
Author: User

Package Com.su.dolphin.utils;import Java.lang.reflect.array;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import java.lang.reflect.Method;/** * * @className: Reflectionutil * @description: Reflection Tool Class * @author: Gaoshuai * @date: August 5, 2015 PM 4:51:49 */public Class Reflectio  nutil{/** * * @title: SetField * @description: Sets the value of a member Traversal * @param owner * @param fieldName * @param value * @throws Exception * @return: void */public static void SetField (Object owner, String Field        Name, Object value) throws Exception {class<?> Ownerclass = Owner.getclass ();        Field field = Ownerclass.getdeclaredfield (FieldName);        Field.setaccessible (TRUE);    Field.set (owner, value);      }/** * * @title: Setfieldall * @description: You can set the value of the field for the parent class * @param owner * @param fieldName * @param value * @throws Exception * @return: void */    public static void Setfieldall (object owner, String fieldName, Object value) throws Exception {class<?>        Ownerclass = Owner.getclass ();        Field field = NULL;                for (class<?> clazz = Ownerclass; Clazz! = Object.class; clazz = Clazz.getsuperclass ()) {try {                field = Clazz.getdeclaredfield (FieldName);                LOGUTIL.D (field + "Find:in" + clazz.getname ());            Break            } catch (Exception e) {LOGUTIL.D (fieldName + "not find" + clazz.getname ());        }} field.setaccessible (True);    Field.set (owner, value); /** * Gets the public properties of an object * * @param owner *, FieldName * @return The Property object * @throws Ex Ception * */public static object GetField (object owner, String fieldName) throws Exception {class<                ?> Ownerclass = Owner.getclass ();  Field field = Ownerclass.getfield (FieldName);              Object property = Field.get (owner);    return property; }/** * Get static public properties of a class * * @param className * Class name * @param fieldName * Genus Sex name * @return The Property object * @throws Exception */public static object Getstaticfield (String className, String Fiel                Dname) throws Exception {class<?> Ownerclass = Class.forName (className);                Field field = Ownerclass.getfield (FieldName);                Object property = Field.get (Ownerclass);    return property;     }/** * Executes an object method * * @param owner * Object * @param methodName * Method Name * @param args * parameter * @return method return value * @throws Exception */public static Object InvokeMethod ( Object owner, String methodName, Object ... args) throws Exception {class<?> Ownerclass = OWNER.GETCL                (); class<?>[] Argsclass = new Class[args.Length]; for (int i = 0, j = args.length; I < J; i++) {if (args[i].getclass () = = Integer.class) {//general functions are int instead of I            Nteger argsclass[i] = Int.class; } else if (args[i].getclass () = = Float.class) {//general functions are int instead of integer argsclass[i] = float.cl            the; The Else if (args[i].getclass () = = Double.class) {//general functions are int instead of integer argsclass[i] = Double.            Class            } else {Argsclass[i] = Args[i].getclass ();        }} method = Ownerclass.getdeclaredmethod (MethodName, Argsclass);        Method.setaccessible (TRUE);    Return Method.invoke (owner, args); }/** * * @title: Invokemethodall * @description: Call all functions, including all functions of the parent class * @param owner * @param m Ethodname * @param args * @return * @throws Exception * @return: Object */public static Object inv Okemethodall (ObjeCT owner, String methodName, Object ... args) throws Exception {class<?> Ownerclass = Owner.getclass (                );                class<?>[] Argsclass = new Class[args.length]; for (int i = 0, j = args.length; I < J; i++) {if (args[i].getclass () = = Integer.class) {//general functions are int instead of I            Nteger argsclass[i] = Int.class; } else if (args[i].getclass () = = Float.class) {//general functions are int instead of integer argsclass[i] = float.cl            the; The Else if (args[i].getclass () = = Double.class) {//general functions are int instead of integer argsclass[i] = Double.            Class            } else {Argsclass[i] = Args[i].getclass ();                }} method = null;                for (class<?> clazz = Ownerclass; Clazz! = Object.class; clazz = Clazz.getsuperclass ()) {try {             method = Clazz.getdeclaredmethod (MethodName, Argsclass);   LOGUTIL.D (method + "Find:in" + clazz.getname ());            return method;                } catch (Exception e) {//e.printstacktrace ();            LOGUTIL.D (MethodName + "not find in" + clazz.getname ());        }} method.setaccessible (True);    Return Method.invoke (owner, args); }/** * Performs a static method of a class * * @param className * Class name * @param methodName * method Name * @param args * parameter array * @return The result returned by the execution method * @throws Exception */public static Object I  Nvokestaticmethod (String className, String methodName, Object ... args) throws Exception {class<?> Ownerclass                = Class.forName (ClassName);                class<?>[] Argsclass = new Class[args.length];        for (int i = 0, j = args.length; I < J; i++) {Argsclass[i] = Args[i].getclass (); } method = Ownerclass.getmethod (MethodName, ARGSCLASS);        Method.setaccessible (TRUE);    return Method.invoke (null, args); }/** * NEW instance * * @param className * Class name * @param args * constructor parameters if no construct parameter, args fills in as null * @return new instance * @throws Exception */public static Object newinstance (String className, Object[] args) throws Nosuchmethodexception, SecurityException, ClassNotFoundException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {return newinstance (className, args, n            ULL); }/** * NEW instance * * @param className * Class name * @param args * constructor parameters if no construct parameter, args fills in as null * @return new instance * @throws Exception */public static Object newinstance (String className, Object[] args, class<?>[] argstype) throws Nosuchmethodexception, SecurityException, ClassNotFoundException, Instantiationexception, Illegalaccessexception, IllegalargumenTexception, invocationtargetexception {class<?> newoneclass = Class.forName (className);                    if (args = = null) {return newoneclass.newinstance ();            } else {constructor<?> cons;                                if (Argstype = = null) {class<?>[] Argsclass = new Class[args.length];                for (int i = 0, j = args.length; I < J; i++) {Argsclass[i] = Args[i].getclass ();            } cons = Newoneclass.getconstructor (Argsclass);            } else {cons = Newoneclass.getconstructor (Argstype);        } return Cons.newinstance (args);     }}/** * is not an instance of a class * * @param obj * instance * @param CLS * class * @return If obj is an instance of this class, returns true */public static Boolean isinstance (Object obj, class<?> cls) {R Eturn Cls.isinstance (obj); /** * Get an element in the array * * @param array * array * @param index * Index * @ Return returns the value of the index component in the specified Array object */public static object Getiteminarray (object array, int index) {return Array.get (AR    Ray, index); }/** * * @title: Getclasslistbypackage * @description: Gets all class * @param ppackage * Under the package @retu RN * @return:class<?> */public static class<?> Getclasslistbypackage (String ppackage) {Pa        Ckage _package = Package.getpackage (ppackage);                class<?> _list = _package.getclass ();    return _list; }}



Attention:

1. Calling the GetMethods method outputs its own public method and the public method of the parent class object. The Getdeclaredmethods method is called to output its own public, protected, private methods.

2. If you want to get the private function of the parent class

    public static method Getdeclaredmethod (Object object, String methodName, class<?> ... parametertypes) {          method method = null;                    for (class<?> clazz = Object.getclass (); Clazz! = Object.class; clazz = Clazz.getsuperclass ()) {              try {                  meth od = Clazz.getdeclaredmethod (methodName, parametertypes);                  return method;              } catch (Exception e) {              }          }                    return null;      }  


Java Reflection Tool Class

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.