java反射笔记
package test1125; public class classTest { public static void main(String[] args) { try { // 获取Class对象的三种方式 System.out.println("根据类名: \t" + User.class); System.out.println("根据对象: \t" + new User().getClass()); Class<?> userClass = Class.forName("test1125.User"); System.out.println("根据全限定类名:\t" + userClass); // 常用的方法 System.out.println("获取全限定类名:\t" + userClass.getName()); System.out.println("获取类名:\t" + userClass.getSimpleName()); System.out.println("实例化:\t" + userClass.getDeclaredConstructor().newInstance()); } catch (ClassNotFoundException e) { System.out.println("找不到类: " + e.getMessage()); } catch (Exception e) { System.out.println("发生异常: " + e.getMessage()); } } } // User类的定义 package test1125; public class User { private String name; public User() { this.name = "默认用户"; } @Override public String toString() { return "User{name='" + name + "'}"; } }