How does one access a method from an external jar at runtime?

前端 未结 3 637
刺人心
刺人心 2021-01-12 15:51

This is a continuation of the question posted in: How to load a jar file at runtime

I am uncertain as to how to continue to the method invocation level. From my und

3条回答
  •  长发绾君心
    2021-01-12 16:12

    The code example

    ClassLoader loader = URLClassLoader.newInstance(
        new URL[] { yourURL },
        getClass().getClassLoader()
    );
    Class clazz = Class.forName("mypackage.MyClass", true, loader);
    Class runClass = clazz.asSubclass(Runnable.class);
    // Avoid Class.newInstance, for it is evil.
    Constructor ctor = runClass.getConstructor();
    Runnable doRun = ctor.newInstance();
    doRun.run();
    

    assumes that the class you are loading implements a particular interface Runnable, and therefore it's reasonale to cast to that type using asSubclass() and invoke run().

    What do you know about the classes you are loading? Can you assume that they implement a particualr interface? If so adjust the asSubClass() line to reference the interafce you prefer.

    Then, yes if you are working with instance methods create an instance using the contructor, ctor in the example.

    There is no starting of a thread in the example. Creating a new thread would just have needed a couple of lines more code

    Thread myThread = new Thread(doRun);
    myThread.start();
    

提交回复
热议问题