public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { //
需求:执行类中所有以test开头的方法
Scanner in = new Scanner(System.in); String className = in.nextLine(); //动态加载类 Class<?> clas = Class.forName(className); Method[] methods = clas.getMethods();//继承 公共方法 Method[] declaredMethods = clas.getDeclaredMethods();//非继承 所有方法 //创建一个不可重复集合set Set<Method> set = new HashSet<Method>(); for (Method method : methods) { set.add(method); } for (Method method : declaredMethods) { set.add(method); } //创建一个list集合存储以该类中所有以test开头的方法 List<Method> list = new ArrayList<Method>(); for (Method method : set) { //System.out.println(method); //打桩 if (method.getName().startsWith("test")) { list.add(method); } } for (Method method : list) { //System.out.println(method); //invoke是方法执行完毕返回的对象 Object invoke = method.invoke(clas.newInstance(), null); System.out.println("执行完毕"); } }
以上就是关于Java反射机制的实例代码的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号