Person person =newPerson();Class clazzA =Class.forName("com.demo.Person");Class clazzB =person.getClass();Class clazzC =Person.class;System.out.println(clazzA.hashCode());System.out.println(clazzB.hashCode());System.out.println(clazzC.hashCode());
三者hashCode无异,同一Class对象也
获取属性和方法
既获之类,进而获之属性与方法,实例之。
Class clazz =Class.forName("com.demo.Person");// 获取所有方法Method[] methods =clazz.getDeclaredMethods();for (Method method : methods) {System.out.println(method);}// 获取所有字段Field[] fields =clazz.getDeclaredFields();for (Field field : fields) {System.out.println(field);}// 实例化类Constructor constructor =clazz.getConstructor(String.class,Integer.class);Person person = (Person) constructor.newInstance("Billy",15);// 修改私有字段Field field =clazz.getDeclaredField("age");field.setAccessible(true);field.set(person,18);System.out.println(person);// 调用私有方法Method method =clazz.getDeclaredMethod("action",String.class);method.setAccessible(true);method.invoke(person,"PRIVATE METHOD GET");
publicclassDBConnector {privatestaticDBConnector instance =newDBConnector();publicstaticDBConnectorgetDBConnector() {return instance; }privateDBConnector() {// code for connecting to DB } }
Class clazz =Class.forName("java.lang.Runtime");Object runTime =clazz.getMethod("getRuntime").invoke(null);clazz.getMethod("exec",String.class).invoke(runTime,"calc");
也可以获取Runtime的私有构造器去构造Runtime对象
Class clazz =Class.forName("java.lang.Runtime");Constructor constructor =clazz.getDeclaredConstructor();constructor.setAccessible(true);clazz.getMethod("exec",String.class).invoke(constructor.newInstance(),"calc");
Class clazz =Class.forName("java.lang.ProcessBuilder");clazz.getMethod("start").invoke(clazz.getConstructor(List.class).newInstance(Arrays.asList("calc")));
Class clazz =Class.forName("java.lang.ProcessBuilder");clazz.getMethod("start").invoke(clazz.getConstructor(String[].class).newInstance(newString[][]{{"calc"}}));