zoukankan      html  css  js  c++  java
  • Java通过反射实现实例化

    public static void main(String[] args) throws Exception {
    
            User user= (User) test(User.class);
            System.out.println(user.getMoney());
            invokeTest(user,"getMoneyT");
        }
        
        /**通过反射获取实例
         * @param clazz类,如user.class
         * @return 类实例
         * @throws Exception
         */
        static Object test(Class clazz) throws Exception{
            //clazz.newInstance();//实例化一个类,前提是该类存在无参构造参数
            Constructor constructor=clazz.getConstructor(String.class);//得到构造器,String.class是即将实例化类clazz的构造参数的类型
            Object obj= constructor.newInstance("test");//传入一个参数进行实例化
            return obj;
        }
        /**调用指定方法
         * @param obj对象
         * @param methodName要调用的方法名
         * @throws Exception
         */
        static void invokeTest(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 (m.getName().equals(methodName)) {
                    m.invoke(obj, null);//调用无参方法
                }
                
            }
            Method methods=obj.getClass().getMethod(methodName, null);//根据方法名和参数直接调用方法,方法无参传null
            methods.invoke(obj, null);
        }
        /**通过反射获取字段
         * @param clazz
         * @throws Exception
         */
        static void filed(Class clazz) throws Exception{
            Field[] fs=clazz.getDeclaredFields();//当前类的字段,包括私有
            //fs=clazz.getFields();//所有公共字段
            for (Field field : fs) {
                System.out.println(field.getName());
            }
        }
  • 相关阅读:
    Hadoop
    Mapreduce
    ssh原理
    HDFS
    Centos
    创建jira插件
    新型的领导者是一名推动者,而不是一名发号施令者
    上善若水,虚怀若谷
    GoAhead 嵌入式web
    Eclipse基金会
  • 原文地址:https://www.cnblogs.com/changshuo/p/3281261.html
Copyright © 2011-2022 走看看