获取Class对象的方式:
1. Class.forName("全类名");
将字节码加载进内存,返回Class对象,多用于配置文件,将类名定义在配置文件中,读取文件,加载类
2. 类名.class ;
通过类名的属性class获取,多用于参数的传递
3. 对象.getClass();
getClass()方法在object类中定义者,多用于对象的获取字节码方式
package Study; class User { public String toString() { return "User: 成功"; } public void func() { System.out.println("User: func"); } } public class reflect { public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { System.out.println("方法一:"); Class<User> method1 = User.class; User user1 = method1.newInstance(); user1.func(); System.out.println("method1: "+method1.toString()); System.out.println("方法二:"); Class<?> method2 = Class.forName("Study.User"); User user2 = (User) method2.newInstance(); user2.func(); System.out.println("method2: "+method2.toString()); System.out.println("方法三:"); Class<?> method3 = new User().getClass(); User user3 = (User) method3.newInstance(); user3.func(); System.out.println("method3: "+method3.toString()); } }
原文:https://www.cnblogs.com/oytt/p/14368840.html