How to load My Jar to ClassPath at runtime through Java Coding?

前端 未结 1 1815
说谎
说谎 2021-01-29 06:14

I am working with Swing in Net Beans. I have my own jar which contains classes and methods inside it. I will call those classes and methods using JAVA Reflection API but before

相关标签:
1条回答
  • 2021-01-29 06:58

    You can load classes at run time through the use of a ClassLoader, take a look at URLClassLoader for example

    File yourJarFile = ...;
    URLClassLoader classLoader = new URLClassLoader(new URL[]{yourJarFile.toURI().toURL()});
    

    This will then allow you to load classes and instantiate them...

    Class class = classLoader.loadClass("fully.qualified.packagename.to.your.AwesomeClass");
    

    You can then instantiate them using something like...

    Object obj = class.newInstance();
    

    Or reflection if you want to use a specific constructor. Just remember, you won't be able to reference these classes directly within the current class loader context, as the current class loader knows nothing about them

    0 讨论(0)
提交回复
热议问题