Class.forName("full-name")
包名、类名、父类、属性、方法、构造方法.....
JVM自动生成一个Class对象
;默认的类加载器
--父-->
扩展类加载器 --父-->
引导类加载器注意:父加载器不是父类
@Test
public void getClassLoader() {
Class<?> clazz = String.class;
ClassLoader classLoader = clazz.getClassLoader();
System.out.println(classLoader);
// null, 根加载器并不是由Java语言实现的,因此拿不到根加载器对象
}
@Test
public void getClassLoader2() throws ClassNotFoundException {
// this.getClass().getClassLoader();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<?> clazz = classLoader.loadClass("com.example.concrete.common.domain.User");
System.out.println(classLoader);
System.out.println(classLoader.getParent());
}
打印结果
sun.misc.Launcher$AppClassLoader@18b4aac2
sun.misc.Launcher$ExtClassLoader@51efea79
方式一:对象.getClass()
String str = "hello";
Class<?> clazz = str.getClass();
方式二:类.class
Class<?> clazz = String.class;
方式三:Class. forName() 动态加载类
// 静态方法 forName("类的全限定名")
Class<?> clazz3 = Class.forName("java.lang.String");
// ClassLoader 的默认实现就是双亲委托
public abstract class ClassLoader {
//每个类加载器都有个父加载器
private final ClassLoader parent;
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
protected final Class<?> defineClass(String name, byte[] b, int off, int len) throws ClassFormatError {
return defineClass(name, b, off, len, null);
}
}
// name: 类的全限定名
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* classpath 就是一组目录的集合;classpath 是 JVM 用到的一个环境变量,它用来指示 JVM 如何搜索class
* 在启动 JVM 时设置 classpath 变量
* java -cp or java -classpath .;C:\work\project1\bin;C:\shared abc.xyz.Hello
* 如果不设置,JVM 默认的 classpath 为. 即当前目录
*/
String classpath = System.getProperty("java.class.path");
Properties properties = System.getProperties();
Set<String> strings = properties.stringPropertyNames();
for (String string : strings) {
System.out.println(string);
}
/**
* 若以“/”开头的,表示要从项目的 ClassPath 开始的( /mapper/xxx.xml ),
* 如果前面没有这个“/”,那么表示的就是相对于该类的路径继续往下
*/
URL resource = classLoader.getResource(""); // file:/.../target/classes/
URL resource1 = classLoader.getResource("bean.xml"); // file:/.../target/classes/bean.xml
BOOT-INF/classes
Maven 项目目录
src
|-- main
|-- java
|-- com.xxx
|-- resources
|-- application.yml
编译后目录
target
|-- classes
|-- com.xxx
|-- application.yml
打包的 jar 解压后目录
|-- BOOT-INF
|-- classes
|-- com.xxx
|-- application.yml
|-- lib
|-- org.springframework.boot.loader...
引用 classpath 路径下的文件,只需在文件名前加 classpath:
classpath:application-*.xml
# 子目录
classpath:config/*.xml
# **/ 表示任意目录
classpath:**/bean.xml
classpath
在当前classpath 中查找,只加载第一个 classpath 路径classpath*
不仅包含 class 路径, 还包括 jar 文件(classpath目录)classpath*
会从所有的classpath中加载文件classpath:*.xml
classpath*:config.xml