add demo for volatile keyword and Class loader
This commit is contained in:
56
src/main/java/loader/CustomLoader.java
Normal file
56
src/main/java/loader/CustomLoader.java
Normal file
@@ -0,0 +1,56 @@
|
||||
|
||||
package loader;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class CustomLoader extends ClassLoader{
|
||||
|
||||
private String classPath;
|
||||
|
||||
public CustomLoader(String classPath) {
|
||||
this.classPath = classPath;
|
||||
}
|
||||
|
||||
private byte[] loadClassBytes(String className) {
|
||||
String path = STR."\{classPath}\{File.separatorChar}\{className.replace('.', File.separatorChar)}.class".trim();
|
||||
// File file = new File("C:\\Users\\wjluk\\projects\\java_multithread\\src\\main\\java\\loader\\LoaderTest.class");
|
||||
File file = new File(path);
|
||||
System.out.println(file.exists());
|
||||
try (InputStream is = new FileInputStream(path);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
byte[] buffer = new byte[4096];
|
||||
int bytesRead;
|
||||
while ((bytesRead = is.read(buffer)) != -1) {
|
||||
baos.write(buffer, 0, bytesRead);
|
||||
}
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected Class<?> findClass(String name) throws ClassNotFoundException {
|
||||
byte[] classBytes = loadClassBytes(name);
|
||||
if (classBytes == null) {
|
||||
throw new ClassNotFoundException();
|
||||
}
|
||||
return defineClass(name, classBytes, 0, classBytes.length);
|
||||
}
|
||||
|
||||
static void main(String[] args) throws Exception {
|
||||
CustomLoader loader = new CustomLoader(" D:\\");
|
||||
Class<?> clazz = loader.loadClass("LoaderTest");
|
||||
Object obj = clazz.newInstance();
|
||||
clazz.getMethod("greeting").invoke(obj);
|
||||
System.out.println(clazz.getClassLoader());
|
||||
|
||||
System.out.println("---------------------for parent loader-------------------");
|
||||
ClassLoader classLoader = loader.getClass().getClassLoader();
|
||||
while (classLoader != null) {
|
||||
System.out.println( "\t" + classLoader);
|
||||
classLoader = classLoader.getParent();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user