In Java9, how can I reflect class loading if I don't know it?

Suppose I have an application that gives a known name and a package class, I need to load this class and call some methods from it. Let's say this class is available in another java-bank ("library").

Until now, before java 9, since all classes in the classpath were accessible, it would be easy to achieve this.

However, since Java 9, if the module package is not required for the module application, the library class is not available.

How can I achieve the same behavior using modular jars?

Example:

This is my application:

// This is defined in ReflectionApp.jar
// ReflectionApp
// └── src
//     ├── module-info.java
//     └── org
//         └── reflection
//             └── app
//                 └── ReflectionApp.java
//
package org.reflection.app;

import java.lang.reflect.Method;

public class ReflectionApp {
    private static final String PACKAGE = "org.reflection.lib";
    private static final String CLASS = "ReflectiveClass";
    private static final String METHOD = "doSomeWork";

    public static void main(String[] args) throws Exception {

        // This will not work using java9
        Class<?> klass = Class.forName(String.format("%s.%s", PACKAGE, CLASS));
        Object obj = klass.getDeclaredConstructor().newInstance();
        Method meth = klass.getDeclaredMethod(METHOD);
        meth.invoke(obj);
    }
}

And this is my library

// This is defined in ReflectionLib.jar
// ReflectionLib
// └── src
//     ├── module-info.java
//     └── org
//         └── reflection
//             └── lib
//                 └── ReflectiveClass.java
//
package org.reflection.lib;

public class ReflectiveClass {

    public void doSomeWork() {
        System.out.println("::: Doing some work!");
    }
}

For now, if I try to call it like this (assuming all banks are created and available in the lib directory):

java --module-path lib -m ReflectionApp/org.reflection.app.ReflectionApp

Then i get a Exception in thread "main" java.lang.ClassNotFoundException: org.reflection.lib.ReflectiveClass

--- DECISION ---

@Nicolai , --add-modules .

⇒  java --module-path lib --add-modules ReflectionLib -m ReflectionApp/org.reflection.app.ReflectionApp
::: Doing some work!
+6
2

, , " " . .

, . , --add-modules library, .

, " " " " library ", ". , , , . :

  • ,

2., module library { exports org.reflection.lib; }, . , , API .

. org.reflection.lib ReflectiveClass , . :

  • (, )
  • (, )

, , Java 9.

+5

requires module-info.java, . , . --add-modules:

--add-modules <module-name>

<module-name> ReflectionLib.

+1

Source: https://habr.com/ru/post/1016346/


All Articles