How to replace classes in applications running in Java?

I have a class named namegenerator I can use it to generate names based on a given logic Then I write a testnamegeneration class with a method that requires the user to enter a letter and generate a name based on the name Now I want to change the logic in the namegeneration class and apply that particular change without stopping the application

I do this in order to learn more about class loader. Can someone explain the key concepts I have to learn in order to do this or any reference to the website?

Solution

This is a job test Test every 5 seconds Main() reloads test. From the file system Test1. Class and call test1 hello()

package test;

public class Test1 {
    public void hello() {
        System.out.println("Hello !");
    }
}

public class Test {

    static class TestClassLoader extends ClassLoader {
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (name.equals("test.Test1")) {
                try {
                    InputStream is = Test.class.getClassLoader().getResourceAsStream("test/Test1.class");
                    byte[] buf = new byte[10000];
                    int len = is.read(buf);
                    return defineClass(name,buf,len);
                } catch (IOException e) {
                    throw new ClassNotFoundException("",e);
                }
            }
            return getParent().loadClass(name);
        }
    }

    public static void main(String[] args) throws Exception {
        for (;;) {
            Class cls = new TestClassLoader().loadClass("test.Test1");
            Object obj = cls.newInstance();
            cls.getmethod("hello").invoke(obj);
            Thread.sleep(5000);
        }
    }
}

function. Then change and recompile test1

System.out.println("Hello !!!");

And the test is running You will see test1 Hello output changes

...
Hello !
Hello !
Hello !!!
Hello !!!

This is how Tomcat reloads webapps It has a separate classloader for each webapp and loads a new version in the new classloader The old is GCed, just like any Java object and old class

Note that we use testclassloader to load test1 and call its first method through reflection However, all test1 dependencies will be implicitly loaded into the test1 class loader, that is, all test1 applications will be loaded into the testclassloader by the JVM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>