加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java通过反射调用方法

发布时间:2020-12-14 23:53:03 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method; public class Main { /** * Invokes the methods of an obje

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

 
public class Main {

    /**
     * Invokes the methods of an object using the Reflection api.
     */
    public void invokeMethodsUsingReflection() {

        //Obtain the Class instance
        Class computerClass = Computer.class;

        //Get the methods
        Method[] methods = computerClass.getDeclaredMethods();

        //Create the object that we want to invoke the methods on
        Computer computer = new Computer();

        //Loop through the methods and invoke them
        for (Method method : methods) {
            Object result;
            try {
                //Call the method. Since none of them takes arguments we just
                //pass an empty array as second parameter.
                result = method.invoke(computer,new Object[0]);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
                return;
            } catch (InvocationTargetException ex) {
                ex.printStackTrace();
                return;
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
                return;
            }
            System.out.println(method.getName() + ": " + result);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().invokeMethodsUsingReflection();
    }

    class Computer {

        private String brand = "DELL";
        private String type = "Laptop";
        private int harddiskSize_GB = 300;
        private boolean AntiVirusInstalled = true;

        public String getBrand() {
            return brand;
        }

        public String getType() {
            return type;
        }

        public int getHarddiskSize_GB() {
            return harddiskSize_GB;
        }

        public boolean isAntiVirusInstalled() {
            return AntiVirusInstalled;
        }
    }
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读