Hugh Macdonald
Hugh Macdonald

Reputation: 143

How to dynamically import jar on Runtime. tools.jar

I am trying to import the tools.jar from Java's JDK yet I am getting an InstantiationException whenever I attempt to create a newInstance of a class from the library.

My code so far:

File toolsLib = new File("myjdk/lib/tools.jar");
URLClassLoader myClassLoader = new URLClassLoader(new URL[] { toolsLib.toURL() }, System.class.getClassLoader());
Class vmClass = myClassLoader.loadClass("com.sun.tools.attach.VirtualMachine");
vmClass.newInstance(); //This is where I get an InstantiationException

This is all done within a seperate thread from my main program.

Any help would be greatly appreciated.

Upvotes: 0

Views: 170

Answers (1)

hotzst
hotzst

Reputation: 7526

The constructor of com.sun.tools.attach.VirtualMachine has the modifier protected and takes two arguments. That is why it is not possible to create a new instance using newIntance().

Class.newInstance() will only succeed if the constructor is has zero arguments and is already accessible.

However there are static attach methods defined on VirtualMachine, that can be used to get an instance.

Take also a look at Oracle's documentation on class instantiation.

Upvotes: 1

Related Questions