JP 9 2 Practice Solution
JP 9 2 Practice Solution
JP 9 2 Practice Solution
9-2: ClassLoader
Practice Solutions
Lesson Objectives:
• The Class Loading Overview
• ClassLoader loading procedure
• JDK ClassLoader Class
• ClassLoader Hierarchy
• Custom ClassLoader
• Class Linking
Vocabulary:
BootStrap class loader The ClassLoader that loads classes from the core Java libraries
Extension class loader The ClassLoader that loads classes from the JAR files located in the extensions directories
Application class loader The ClassLoader that loads the application class, which can come from a directory or JAR
file on the class path
Write a program to use the ClassLoader to load the Loaded Class and instantiate the Loaded Class instance.
Given the following class that will be loaded by the custom class loader:
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
1. Write a MyclassLoader that inherits the abstract ClassLoader class to override the findClass method, and that will load the HelloClass
from the specified Path
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
FileInputStream fis = new FileInputStream(file);
return defineClass(name,data,0,data.length);
} catch (IOException e) {
e.printStackTrace();
}
return super.findClass(name);
}
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
2
2. Write a TestClassLoader program to load the HelloClass
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
if(c1 != null){
try {
Object t = c1.newInstance();
Method method = c1.getDeclaredMethod("sayHello");
method.invoke(t);
} catch (InstantiationException | IllegalAccessException
| NoSuchMethodException
| SecurityException |
IllegalArgumentException |
InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
3. Modify the TestClassLoader to load the class twice, and check the output to observe two HelloClass to be loaded and initialized
C:\test\classloader\findclass>java TestClassLoader
HelloClass has been initialized
HelloClass has been initialized
Hello Class Loader
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.