1.reflect反射机制:反射机制是一个动态机制,允许在运行的过程中去确定类对象,再实例化确定方法的调用,属性的操作。
2.可长变参数:dk5以后出的 可变长参数 必须是一个方法中最后的一个参数
method.getDeclaredMethod:获取所有方法(包含了私密方法、但不能访问)在接下来加入 , method.setAuccessible(true);可以强行获取私密方法 但是并不适合
public class Test2 { public static void main(String[] args) throws Exception { //1.定位到当前的目录 并通过URI编译 File dir = new File( // Test2.class.getClassLoader().getResource(".").toURI() 这个获取的是 //C:\Users\tedu\IdeaProjects\JSD2206\out\production\JSD2206 Test2.class.getClassLoader().getResource(".").toURI() //C:\Users\tedu\IdeaProjects\JSD2206\out\production\JSD2206\reflect ); System.out.println(dir); //循环找一下file集合中 有多少个.class文件 File[] subs = dir.listFiles(f -> f.getName().endsWith(".class")); //循环输出 for (File sub : subs) { String fileName = sub.getName(); //根据.class文件名获取类名 例如:Person.class 第一个0代表下标开始的位置 , 第二个代表下表结束的位置 String className = fileName.substring(0, fileName.indexOf(".")); // System.out.println(className); //加载类对象 Test2.class.getPackage().getName() == reflect Class cls = Class.forName( Test2.class.getPackage().getName() + "." + className ); System.out.println("实例化的对象"+cls.getSimpleName()); Object obj = cls.newInstance(); Method[] methods = cls.getDeclaredMethods(); for (Method method : methods) { if (//判断是否无参 method.getParameterCount() == 0 && //判断是否为公开方法 method.getModifiers() == Modifier.PUBLIC && method.getName().contains("s") ) { System.out.println("自动调用:" + method.getName() + "()"); ; method.invoke(obj); } } } } }
2.
public class ArgsDemo { // public static void main(String[] args) { // test(new String[]{"a","b","c"}); 全部变成了数组 // } // // public static void test(String[] arg){ // System.out.println(arg.length); // } public static void main(String[] args) { test(1 ,"a", "b", "c"); } //可以String... 这样的意义为数组中的个数 是不限制的 public static void test(int a ,String... arg) { System.out.println(arg.length); } }