一、Class的概述:Class对象是存储在heap区的
获取Class类:
1、类.class
2、对象.getClass()
3、Class.forName("java.lang.String")
二、Class类的方法:
1、Class.getResource()
App.class.getResource("")取的是当前目录的资源
App.class.getResource("/")取的是classes目录下的资源
String path = Main.class.getResource("/config.properties").getPath(); String path2 = Main.class.getResource("/config.properties").toURI().getPath();
2、Class.getResourceAsStream()
App.class.getResourceAsStream("")取的是当前目录的资源
App.class.getResourceAsStream("/")取的是classes目录下的资源
3、Class.getClassLoader().getResource()
App.class.getClassLoader().getResource("")取的是classes目录下的资源
App.class.getClassLoader().getResource("/")取的是引导类加载器下面的资源。所以为null
三、Constructor:
1、newInstance根据反射创建类的实例的方法
package org.eclipse.winery.repository; import java.lang.reflect.Constructor; import java.net.URISyntaxException; public class Main2 { public static void main(String[] args) throws URISyntaxException, Exception { Constructor<Obj> constructor = builder(Obj.class); Obj obj = constructor.newInstance("myname", 33333); System.out.println(obj); } public static <T> Constructor<T> builder(Class<T> clazz) throws NoSuchMethodException, SecurityException { Constructor<T> constructor = clazz.getConstructor(String.class, int.class); return constructor; } private static class Obj { public String name = "Soar up into the sky with one start!"; public int id = 123456; public Obj(String name, int id) { super(); this.name = name; this.id = id; } @Override public String toString() { return "Obj [name=" + name + ", id=" + id + "]"; } } }