Java的Class类及反射

2021-02-03

Java的Class类及反射

主要是通过代码来进行展示:

普通的实体类:User

Class的测试类:UserTest

反射机制的类:Reflex

 

由于我们使用Maven构建的 java项目

pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.zc.javapro</groupId>
    <artifactId>maven_java</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/cglib/cglib -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.27.0-GA</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                    <compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

1、User

package cn.zc.javapro.mechanism.reflaction;

import java.io.IOException;
import java.io.Serializable;

public class User {
    private Integer userId;
    private String userName;
    private String passWord;

    protected String protectedArg;
    public String publicArg;

    public User() {
    }

    private User(Integer userId) {
        this.userId = userId;
    }

    protected User(Integer userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public User(Integer userId, String userName, String passWord) {
        this.userId = userId;
        this.userName = userName;
        this.passWord = passWord;
    }

    public User(Integer userId, String userName, String passWord, String protectedArg, String publicArg) {
        this.userId = userId;
        this.userName = userName;
        this.passWord = passWord;
        this.protectedArg = protectedArg;
        this.publicArg = publicArg;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getProtectedArg() {
        return protectedArg;
    }

    public void setProtectedArg(String protectedArg) {
        this.protectedArg = protectedArg;
    }

    public String getPublicArg() {
        return publicArg;
    }

    public void setPublicArg(String publicArg) {
        this.publicArg = publicArg;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", protectedArg='" + protectedArg + '\'' +
                ", publicArg='" + publicArg + '\'' +
                '}';
    }

    private String privateMethod(String str) {
        return str;
    }

    protected String protectedMethod(String str) {
        return str;
    }

    public String publicMethod(String str) {
        return str;
    }

    public void testException(String str, Integer i) throws IOException,Exception {

    }
}
User

2、UserTest

package cn.zc.javapro.mechanism.reflaction;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
//import org.objectweb.asm.ClassAdapter;
//import org.objectweb.asm.ClassReader;
//import org.objectweb.asm.ClassWriter;
//import org.objectweb.asm.Label;
//import org.objectweb.asm.MethodAdapter;
//import org.objectweb.asm.MethodVisitor;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.Arrays;

// 这里只是测试了 class ,关于 abstract class 及 interface 需要自己去测

/**
 * Class 类的测试代码,会用了之后就可以熟练的使用反射机制。
 * getFields()与getDeclaredFields()区别:getFields()只能访问类中声明为公有的字段,私有的字段它无法访问.getDeclaredFields()能访问类中所有的字段,与public,private,protect无关
 *
 * getMethods()与getDeclaredMethods()区别:getMethods()只能访问类中声明为公有的方法,私有的方法它无法访问,能访问从其它类继承来的公有方法.getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
 *
 * getConstructors()与getDeclaredConstructors()区别:getConstructors()只能访问类中声明为public的构造函数.getDeclaredConstructors()能访问类中所有的构造函数,与public,private,protect无关
 */
public class UserTest {

    public static void main(String[] args) {
        test15();
    }

    // 1、通过对象可以获得类
    public static void test1() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        System.out.println(c4);
        System.out.println(c4.getName());
        //
        try {
            Class c5 = Class.forName("cn.zc.javapro.mechanism.reflaction.User");
            System.out.println(c5);
            System.out.println(c5.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //2、获取类的所有构造方法
    public static void test2() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //
        Constructor[] constructors;
        // 获取类的所有构造方法
        constructors = c4.getDeclaredConstructors();
        /* 通过getModifiers可以得到构造方法的类型,
         getParameterTypes可以得到构造方法的所有参数,返回的是一个Class数组,
         所以我们如果想获取所有构造方法以及每个构造方法的参数类型,*/
        for (int i = 0; i < constructors.length; i++) {
            System.out.print("{ 类名:" + c4.getName() + ", 构造方法名:" + constructors[i].getName() + ", 作用域:" + Modifier.toString(constructors[i].getModifiers()) + ", 参数: { ");
            Class[] parametertypes = constructors[i].getParameterTypes();
            for (int j = 0; j < parametertypes.length; j++) {
                if(j < parametertypes.length - 1 ) {
                    System.out.print(parametertypes[j].getName() + ", ");
                } else {
                    System.out.print(parametertypes[j].getName());
                }
            }
            System.out.println(" } }");
        }
    }

    // 3、获取类中 所有的public类型的构造方法
    public static void test3() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        // 3、获取类中所有的public类型的构造方法
        Constructor[] constructors;
        // 获取类的所有构造方法
        constructors = c4.getConstructors();
        /* 通过getModifiers可以得到构造方法的类型,
         getParameterTypes可以得到构造方法的所有参数,返回的是一个Class数组,
         所以我们如果想获取所有构造方法以及每个构造方法的参数类型,*/
        for (int i = 0; i < constructors.length; i++) {
            System.out.print("{ 类名:" + c4.getName() + ", 构造方法名:" + constructors[i].getName() + ", 作用域:" + Modifier.toString(constructors[i].getModifiers()) + ", 参数: { ");
            Class[] parametertypes = constructors[i].getParameterTypes();
            for (int j = 0; j < parametertypes.length; j++) {
                if(j < parametertypes.length - 1 ) {
                    System.out.print(parametertypes[j].getName() + ", ");
                } else {
                    System.out.print(parametertypes[j].getName());
                }
            }
            System.out.println(" } }");
        }
    }

    // 4、获取类中特定的构造方法
    public static void test4() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        // 4、获取类中特定的构造方法
        // 我们可以通过 getDeclaredConstructor() 方法传参获取特定参数类型的构造方法,
        // 这里注意是getDeclaredConstructor()不是  getDeclaredConstructors() ,
        // 所以返回的是一个Class对象而不是一个Class数组。

        // 获取无参构造方法直接不传参数,如下所示:
        // 这里要进行异常捕获,因为可能不存在对应的构造方法,打印结果如下:
        Constructor constructorNoArg = null;
        try {
            constructorNoArg = c4.getDeclaredConstructor();
            System.out.println("{ 类名:" + c4.getName() + ", 构造方法名:" + constructorNoArg.getName() + ", 作用域:" + Modifier.toString(constructorNoArg.getModifiers()) + ", 参数: { } }");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        // 如果我们想获取有三个参数分别为 int 和 String 和 String 类型的构造方法,代码如下:
        Constructor constructorArgs = null;
        Class[] p = {Integer.class, String.class, String.class};
        try {
            constructorArgs = c4.getDeclaredConstructor(p);
            System.out.print("{ 类名:" + c4.getName() + ", 构造方法名:" + constructorArgs.getName() + ", 作用域:" + Modifier.toString(constructorArgs.getModifiers()) + ", 参数: { ");
            Class[] parametertypes = constructorArgs.getParameterTypes();
            for (int j = 0; j < parametertypes.length; j++) {
                if(j < parametertypes.length - 1 ) {
                    System.out.print(parametertypes[j].getName() + ", ");
                } else {
                    System.out.print(parametertypes[j].getName());
                }
            }
            System.out.println(" } }");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    //5、调用构造方法
    public static void test5() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //5、调用构造方法
        // 我们先来调用public的方法,如下所示:
        Constructor constructor2 = null;
        Class[] p2 = {Integer.class, String.class, String.class};
        try {
            constructor2 = c4.getDeclaredConstructor(p2);
            // 从这里开始慢慢到了关键的一步,得到类的实例,我们主要借助于newInstance方法,为了方便演示我们将测试类的两个构造方法打印出来.
            User user1 = (User) constructor2.newInstance(1, "admin", "123456");
            System.out.println(user1.toString());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 我们先来调用 private 的方法,那么调用私有构造方法呢,和上面一样,只是我们要设置constructors.setAccessible(true);代码如下:
        Constructor constructor3 = null;
        Class[] p3 = {Integer.class};
        try {
            constructor3 = c4.getDeclaredConstructor(p3);
            ////忽略访问修饰符的检查
            constructor3.setAccessible(true);
            // 从这里开始慢慢到了关键的一步,得到类的实例,我们主要借助于newInstance方法,为了方便演示我们将测试类的两个构造方法打印出来.
            User user1 = (User) constructor3.newInstance(1);
            System.out.println(user1.toString());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    // 6、获取类成员变量
    public static void test6() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //6、获取类成员变量
        Field[] fields = c4.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i]);
            // 上面等同于下面
            /*System.out.println(Modifier.toString(fields[i].getModifiers()) + " " + fields[i].getType().getTypeName()
                    + " " + fields[i].getDeclaringClass().getTypeName() + "." + fields[i].getName());*/
        }
    }

    // 7、获取public 的类成员
    public static void test7() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //6、获取public 的类成员
        Field[] fields = c4.getFields();
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i]);
        }
    }

    // 8、获取这些变量的值
    public static void test8() {
        // 定义一个 User 对象
        User user = new User(1, "admin", "123456", "protected", "public");
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //8、获取这些变量的值
        // Field[] fields = c4.getFields();
        try {
            // private
            Field fieldUserId = c4.getDeclaredField("userId");
            // 因为 userId 是 private
            //忽略访问修饰符的检查
            fieldUserId.setAccessible(true);
            int userId = (Integer) fieldUserId.get(user);
            System.out.println(userId);

            // protected
            Field fieldProtectedArg = c4.getDeclaredField("protectedArg");
            String protectedArg = (String) fieldProtectedArg.get(user);
            System.out.println(protectedArg);

            // public
            //Field fieldPublicArg = c4.getDeclaredField("publicArg");
            Field fieldPublicArg = c4.getField("publicArg");
            String publicArg = (String) fieldPublicArg.get(user);
            System.out.println(publicArg);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 9、设置这些变量的值
    public static void test9() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        // 9、设置这些变量的值
        try {
            // private
            Field fieldUserId = c4.getDeclaredField("userId");
            // 因为 userId 是 private
            //忽略访问修饰符的检查
            fieldUserId.setAccessible(true);
            fieldUserId.set(user, 1);

            // protected
            Field fieldProtectedArg = c4.getDeclaredField("protectedArg");
            fieldProtectedArg.set(user, "protected");

            // public
            //Field fieldPublicArg = c4.getDeclaredField("publicArg");
            Field fieldPublicArg = c4.getField("publicArg");
            fieldPublicArg.set(user, "public");

            System.out.println(user.toString());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 10、获取类中的所有方法
    public static void test10() {
        // 定义一个 User 对象
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        // 10、获取类中的所有方法
        Method[] methods = c4.getDeclaredMethods();
        for(int i=0; i<methods.length; i++) {
            System.out.println(methods[i]);

            // 上面等价于下面
            /*System.out.print(Modifier.toString(methods[i].getModifiers()) + " " + methods[i].getReturnType() + " "
                    + methods[i].getDeclaringClass().getTypeName() + "." + methods[i].getName() + "(");
            Class<?>[] parameterTypes = methods[i].getParameterTypes();
            for(int j=0; j<parameterTypes.length; j++) {
                if(j < parameterTypes.length-1) {
                    System.out.print(parameterTypes[j].getName() + ",");
                } else {
                    System.out.print(parameterTypes[j].getName());
                }
            }
            System.out.print(")");
            Class<?>[] exceptionTypes = methods[i].getExceptionTypes();
            if(exceptionTypes.length != 0) {
                System.out.print(" throws ");
                for(int k=0; k<exceptionTypes.length; k++) {
                    if(k < exceptionTypes.length-1) {
                        System.out.print(exceptionTypes[k].getName() + ",");
                    }else {
                        System.out.print(exceptionTypes[k].getName());
                    }
                }
            }
            System.out.println();*/
        }
    }

    // 11、获取类中的所有 public 方法
    public static void test11() {
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        // 11、获取类中的所有 public 方法
        Method[] methods = c4.getMethods();
        for(int i=0; i<methods.length; i++) {
            System.out.println(methods[i]);
        }
    }

    // 12、获取类中特定的方法
    public static void test12() {
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();

        try {
            Class[] p = {String.class};
            Method method = c4.getDeclaredMethod("privateMethod", String.class);
            //method.setAccessible(true);
            System.out.println(method);

            Class[] p2 = {String.class};
            Method method2 = c4.getDeclaredMethod("protectedMethod", String.class);
            System.out.println(method2);

            Method method3 = c4.getMethod("toString");
            System.out.println(method3);

            Method method4 = c4.getMethod("setPublicArg", String.class);
            System.out.println(method4);

            Class[] p5 = {String.class, Integer.class};
            Method method5 = c4.getMethod("testException", p5);
            System.out.println(method5);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    // 13、调用类中的方法
    public static void test13() {
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();
        //
        // Class<? extends User> clazz = testStr.getClass();
        try {
            //获取到该私有方法的Method对象
            Method method = c4.getDeclaredMethod("privateMethod", String.class);
            //忽略访问修饰符的检查
            method.setAccessible(true);
            Object obj = method.invoke(user, "private");
            System.out.println(obj);

            Method method2 = c4.getDeclaredMethod("protectedMethod", String.class);
            Object obj2 = method2.invoke(user, "protected");
            System.out.println(obj2);

            Method method3 = c4.getMethod("publicMethod", String.class);
            Object obj3 = method3.invoke(user, "public");
            System.out.println(obj3);

            // 2
            //获取该类的Constructor对象
            Constructor constructor = c4.getConstructor(Integer.class, String.class, String.class);
            //Constructor.newInstance方法可以创建该类的实例
            User user1 = (User) constructor.newInstance(1, "hello", "12345");
            System.out.println(user1.toString());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    // 获取类中所有成员变量的 get set 方法
    public static void test14() {
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();//获得实体类名
        //Class clazz=obj.getClass();//获得实体类名
        Field[] fields = c4.getDeclaredFields();//获得属性
        //获得Object对象中的所有方法
        for(Field field:fields){
            PropertyDescriptor pd = null;
            try {
                // System.out.println(field.getName());
                pd = new PropertyDescriptor(field.getName(), c4);
                Method getMethod = pd.getReadMethod();//获得get方法
                //getMethod.invoke(user);//此处为执行该Object对象的get方法
                System.out.println(getMethod);
                Method setMethod = pd.getWriteMethod();//获得set方法
                //setMethod.invoke(user,"参数");//此处为执行该Object对象的set方法
                System.out.println(setMethod);
            } catch (IntrospectionException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取指定类指定方法的参数名
     * 有三种解决方案
     * 1 jdk1.8设置编译器参数之后可以通过反射获得
     * 2 使用javaassist
     * 3 使用asm
     */

    // jdk1.8设置编译器参数之后可以通过反射获得
    // Java 运行时获取方法参数名 https://segmentfault.com/a/1190000019290840
    // javac 编译加上 -parameters
    // 或者 pom.xml 中
    /**
     * <plugin>
     *     <groupId>org.apache.maven.plugins</groupId>
     *     <artifactId>maven-compiler-plugin</artifactId>
     *     <configuration>
     *         <source>1.8</source>
     *         <target>1.8</target>
     *         <compilerArgs>
     *             <arg>-parameters</arg>
     *         </compilerArgs>
     *     </configuration>
     * </plugin>
     */
    public static void test15() {
        User user = new User();
        // 1、通过对象可以获得 类
        Class c4 = user.getClass();//获得实体类名
        Method method = null;
        try {
            method = c4.getDeclaredMethod("publicMethod", String.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter.getType().getName() + " " + parameter.getName());
        }
    }

    // 获取方法的参数变量名称 -- 使用javaassist
    public static void test16() {
        String[] strings = getMethodVariableName("cn.zc.javapro.mechanism.reflaction.User", "publicMethod");
        System.out.println(Arrays.toString(strings));
    }
    /**
     * 获取方法的参数变量名称 -- 使用javaassist
     * @param classname
     * @param methodname
     * @return
     */
    public static String[] getMethodVariableName(String classname,String methodname){
        try{
            ClassPool pool = ClassPool.getDefault();
            CtClass cc = pool.get(classname);
            CtMethod cm = cc.getDeclaredMethod(methodname);
            MethodInfo methodInfo = cm.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            String[] paramNames = new String[cm.getParameterTypes().length];
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
            if (attr != null)  {
                int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
                for (int i = 0; i < paramNames.length; i++){
                    paramNames[i] = attr.variableName(i + pos);
                    // System.out.println(paramNames[i]);
                }
                return paramNames;
            }
        }catch(Exception e){
            System.out.println("getMethodVariableName fail "+e);
        }
        return null;
    }

    // 使用asm https://www.cnblogs.com/relucent/p/6525821.html


}
UserTest

3、Reflex  -- 有待进一步完善

package cn.zc.javapro.mechanism.reflaction;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Reflex {
    /**
     * 获取无参构造函数
     * @param className
     * @return
     */
    public static Object createObject(String className) {
        Class[] pareTyples = new Class[]{};
        Object[] pareVaules = new Object[]{};

        try {
            Class r = Class.forName(className);
            return createObject(r, pareTyples, pareVaules);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取无参构造方法
     * @param object
     * @return
     */
    /*public static Object createObject(Object object) {
        Class[] pareTyple = new Class[]{};
        Object[] pareVaules = new Object[]{};
        Class clazz = object.getClass(); //获得实体类名
        return createObject(clazz, pareTyple, pareVaules);
    }*/

    /**
     * 获取无参构造方法
     * @param clazz
     * @return
     */
    public static Object createObject(Class clazz) {
        Class[] pareTyple = new Class[]{};
        Object[] pareVaules = new Object[]{};

        return createObject(clazz, pareTyple, pareVaules);
    }

    /**
     * 获取一个参数的构造函数  已知className
     *
     * @param className
     * @param pareTyple
     * @param pareVaule
     * @return
     */
    public static Object createObject(String className, Class pareTyple, Object pareVaule) {

        Class[] pareTyples = new Class[]{pareTyple};
        Object[] pareVaules = new Object[]{pareVaule};

        try {
            Class r = Class.forName(className);
            return createObject(r, pareTyples, pareVaules);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 获取单个参数的构造方法 已知类
     *
     * @param clazz
     * @param pareTyple
     * @param pareVaule
     * @return
     */
    public static Object createObject(Class clazz, Class pareTyple, Object pareVaule) {
        Class[] pareTyples = new Class[]{pareTyple};
        Object[] pareVaules = new Object[]{pareVaule};

        return createObject(clazz, pareTyples, pareVaules);
    }

    /**
     * 获取多个参数的构造方法 已知className
     * @param className
     * @param pareTyples
     * @param pareVaules
     * @return
     */
    public static Object createObject(String className, Class[] pareTyples, Object[] pareVaules) {
        try {
            Class r = Class.forName(className);
            return createObject(r, pareTyples, pareVaules);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 获取构造方法
     *
     * @param clazz
     * @param pareTyples
     * @param pareVaules
     * @return
     */
    public static Object createObject(Class clazz, Class[] pareTyples, Object[] pareVaules) {
        try {
            Constructor ctor = clazz.getDeclaredConstructor(pareTyples);
            ctor.setAccessible(true);
            return ctor.newInstance(pareVaules);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 获取多个参数的方法
     * @param obj
     * @param methodName
     * @param pareTyples
     * @param pareVaules
     * @return
     */
    public static Object invokeInstanceMethod(Object obj, String methodName, Class[] pareTyples, Object[] pareVaules) {
        if (obj == null) {
            return null;
        }

        try {
            //调用一个private方法 //在指定类中获取指定的方法
            Method method = obj.getClass().getDeclaredMethod(methodName, pareTyples);
            method.setAccessible(true);
            return method.invoke(obj, pareVaules);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取一个参数的方法
     * @param obj
     * @param methodName
     * @param pareTyple
     * @param pareVaule
     * @return
     */
    public static Object invokeInstanceMethod(Object obj, String methodName, Class pareTyple, Object pareVaule) {
        Class[] pareTyples = {pareTyple};
        Object[] pareVaules = {pareVaule};

        return invokeInstanceMethod(obj, methodName, pareTyples, pareVaules);
    }

    /**
     * 获取无参方法
     * @param obj
     * @param methodName
     * @return
     */
    public static Object invokeInstanceMethod(Object obj, String methodName) {
        Class[] pareTyples = new Class[]{};
        Object[] pareVaules = new Object[]{};

        return invokeInstanceMethod(obj, methodName, pareTyples, pareVaules);
    }


    /**
     * 无参静态方法
     * @param className
     * @param method_name
     * @return
     */
    public static Object invokeStaticMethod(String className, String method_name) {
        Class[] pareTyples = new Class[]{};
        Object[] pareVaules = new Object[]{};

        return invokeStaticMethod(className, method_name, pareTyples, pareVaules);
    }

    /**
     * 获取一个参数的静态方法
     * @param className
     * @param method_name
     * @param pareTyple
     * @param pareVaule
     * @return
     */
    public static Object invokeStaticMethod(String className, String method_name, Class pareTyple, Object pareVaule) {
        Class[] pareTyples = new Class[]{pareTyple};
        Object[] pareVaules = new Object[]{pareVaule};

        return invokeStaticMethod(className, method_name, pareTyples, pareVaules);
    }

    /**
     * 获取多个参数的静态方法
     * @param className
     * @param method_name
     * @param pareTyples
     * @param pareVaules
     * @return
     */
    public static Object invokeStaticMethod(String className, String method_name, Class[] pareTyples, Object[] pareVaules) {
        try {
            Class obj_class = Class.forName(className);
            return invokeStaticMethod(obj_class, method_name, pareTyples, pareVaules);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 无参静态方法
     * @param method_name
     * @return
     */
    public static Object invokeStaticMethod(Class clazz, String method_name) {
        Class[] pareTyples = new Class[]{};
        Object[] pareVaules = new Object[]{};

        return invokeStaticMethod(clazz, method_name, pareTyples, pareVaules);
    }

    /**
     * 一个参数静态方法
     * @param clazz
     * @param method_name
     * @param classType
     * @param pareVaule
     * @return
     */
    public static Object invokeStaticMethod(Class clazz, String method_name, Class classType, Object pareVaule) {
        Class[] classTypes = new Class[]{classType};
        Object[] pareVaules = new Object[]{pareVaule};

        return invokeStaticMethod(clazz, method_name, classTypes, pareVaules);
    }

    /**
     * 多个参数的静态方法
     * @param clazz
     * @param method_name
     * @param pareTyples
     * @param pareVaules
     * @return
     */
    public static Object invokeStaticMethod(Class clazz, String method_name, Class[] pareTyples, Object[] pareVaules) {
        try {
            Method method = clazz.getDeclaredMethod(method_name, pareTyples);
            method.setAccessible(true);
            return method.invoke(null, pareVaules);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static Object getFieldObject(String className, Object obj, String filedName) {
        try {
            Class obj_class = Class.forName(className);
            return getFieldObject(obj_class, obj, filedName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getFieldObject(Class clazz, Object obj, String filedName) {
        try {
            Field field = clazz.getDeclaredField(filedName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void setFieldObject(Class clazz, Object obj, String filedName, Object filedVaule) {
        try {
            Field field = clazz.getDeclaredField(filedName);
            field.setAccessible(true);
            field.set(obj, filedVaule);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setFieldObject(String className, Object obj, String filedName, Object filedVaule) {
        try {
            Class obj_class = Class.forName(className);
            setFieldObject(obj_class, obj, filedName, filedVaule);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static Object getStaticFieldObject(String className, String filedName) {
        return getFieldObject(className, null, filedName);
    }

    public static Object getStaticFieldObject(Class clazz, String filedName) {
        return getFieldObject(clazz, null, filedName);
    }

    public static void setStaticFieldObject(String classname, String filedName, Object filedVaule) {
        setFieldObject(classname, null, filedName, filedVaule);
    }

    public static void setStaticFieldObject(Class clazz, String filedName, Object filedVaule) {
        setFieldObject(clazz, null, filedName, filedVaule);
    }

}
Reflex

 

posted @ 2021-02-03 22:18  秦时明月0515  阅读(94)  评论(0编辑  收藏  举报