Answer to Question #33360 in Java | JSP | JSF for Aasif Ali

Question #33360
how to access classes from two different packages stored at different locations on the hard disk?
1
Expert's answer
2020-12-22T20:10:58-0500

Use ClassLoader fot this kind of situations Detailedtutorial can be found, for example, here: https://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html

Your further search tags are: java, class loader,dynamic runtime class load

Here is an example.

How you prepare class for loading:


public class MyClassLoader extends ClassLoader{

 publicMyClassLoader(ClassLoader parent) {
 super(parent);
 }

 public ClassloadClass(String name) throws ClassNotFoundException {
 if(!"reflection.MyObject".equals(name))
 return super.loadClass(name);

 try {
 Stringurl = "file:C:/data/projects/tutorials/web/WEB-INF/" +
 "classes/reflection/MyObject.class";
 URL myUrl = new URL(url);
 URLConnection connection = myUrl.openConnection();
 InputStream input = connection.getInputStream();
 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
 intdata = input.read();

 while(data != -1){
 buffer.write(data);
 data = input.read();
 }

 input.close();

 byte[]classData = buffer.toByteArray();

 returndefineClass("reflection.MyObject",
 classData, 0, classData.length);

 } catch(MalformedURLException e) {
 e.printStackTrace();
 } catch(IOException e) {
 e.printStackTrace();
 }

 returnnull;
 }

}

And how you load it:
public static void main(String[] args) throws
 ClassNotFoundException,
 IllegalAccessException,
 InstantiationException {

 ClassLoaderparentClassLoader = MyClassLoader.class.getClassLoader();
 MyClassLoaderclassLoader = new MyClassLoader(parentClassLoader);
 ClassmyObjectClass = classLoader.loadClass("reflection.MyObject");

 AnInterface2 object1 =
 (AnInterface2) myObjectClass.newInstance();

 MyObjectSuperClassobject2 =
 (MyObjectSuperClass) myObjectClass.newInstance();

 //create newclass loader so classes can be reloaded.
 classLoader =new MyClassLoader(parentClassLoader);
 myObjectClass= classLoader.loadClass("reflection.MyObject");

 object1 =(AnInterface2) 
myObjectClass.newInstance();
 object2 =(MyObjectSuperClass) myObjectClass.newInstance();

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS