Let's suppose that we have the Guava JAR in the D:/Java Modern Challenge/Code/lib/ folder, and we want to create an instance of CountingInputStream and read one byte from a file.
First, we define a URL[] array for the Guava JAR, as follows:
URL[] classLoaderUrls = new URL[] {
new URL(
"file:///D:/Java Modern Challenge/Code/lib/guava-16.0.1.jar")
};
Then, we will define URLClassLoader for this URL[] array:
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
Next, we will load the target class (CountingInputStream is a class that counts the number of bytes that are read from InputStream):
Class<?> cisClass = urlClassLoader.loadClass(
"com.google.common.io.CountingInputStream");
Once the target class has been loaded, we can fetch its constructor (CountingInputStream has a single constructor that wraps the given InputStream):
Constructor<?> constructor
= cisClass.getConstructor(InputStream.class);
Furthermore, we can create an instance of CountingInputStream via this constructor:
Object instance = constructor.newInstance(
new FileInputStream​(Path.of("test.txt").toFile()));
In order to ensure that the returned instance is operational, let's call two of its methods (the read() method reads a single byte at once, while the getCount() method returns the number of read bytes):
Method readMethod = cisClass.getMethod("read");
Method countMethod = cisClass.getMethod("getCount");
Next, let's read a single byte and see what getCount() returns:
readMethod.invoke(instance);
Object readBytes = countMethod.invoke(instance);
System.out.println("Read bytes (should be 1): " + readBytes); // 1