Home  >  Article  >  Java  >  Example code about Java reflection mechanism

Example code about Java reflection mechanism

零下一度
零下一度Original
2017-07-17 13:35:051482browse

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//

Requirement: Execute all methods starting with test in the class

    Scanner in = new Scanner(System.in);
    String className = in.nextLine();
    //动态加载类
    Class6b3d0130bba23ae47fe2b8e8cddf0195 clas = Class.forName(className);
    Method[] methods = clas.getMethods();//继承 公共方法
    Method[] declaredMethods = clas.getDeclaredMethods();//非继承 所有方法
    
    //创建一个不可重复集合set
    Set4f4c080df8bae601f1e89959feb25b5a set = new HashSet4f4c080df8bae601f1e89959feb25b5a();
    for (Method method : methods) {
        set.add(method);
    }
    for (Method method : declaredMethods) {
        set.add(method);
    }
    
    //创建一个list集合存储以该类中所有以test开头的方法
    List4f4c080df8bae601f1e89959feb25b5a list = new ArrayList4f4c080df8bae601f1e89959feb25b5a();
    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("执行完毕");
    }
    
}

The above is the detailed content of Example code about Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn