zoukankan      html  css  js  c++  java
  • Java反射机制练习

    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("执行完毕");
    	}
    	
    }
  • 相关阅读:
    10000个线程更新同一行数据
    CountDownLatchTest
    创建 oracle dblin
    extjs日期控件使用
    JAVA Date超强工具类,可直接取代util.Date使用
    JSP&Servlet学习手册
    JAVA 文本 TXT 操作工具类
    Leetcode 526.优美的排列
    Leetcode 525.连续数组
    Leetcode 523.连续的子数组和
  • 原文地址:https://www.cnblogs.com/chentging/p/7111425.html
Copyright © 2011-2022 走看看