In Java, is it possible to know whether a class has already been loaded?

前端 未结 5 419
不知归路
不知归路 2020-11-27 03:55

Is it possible to know whether a Java class has been loaded, without attempting to load it? Class.forName attempts to load the class, but I don\'t want

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 04:35

    If you're in control of the source of the classes for which you are interested in whether they are loaded or not (which I doubt, but you don't state in your question), then you could register your load in a static initializer.

    public class TestLoaded {
        public static boolean loaded = false;
        public static void main(String[] args) throws ClassNotFoundException {
            System.out.println(loaded);
            ClassToTest.reportLoaded();
            System.out.println(loaded);
        }
        static class ClassToTest {
            static {
                System.out.println("Loading");
                TestLoaded.loaded = true;
            }
            static void reportLoaded() {
                System.out.println("Loaded");
            }
        }
    }
    

    Output:

    false
    Loading
    Loaded
    true
    

提交回复
热议问题