Restart myself - can I reinitialize everything from scratch?

后端 未结 6 1440
無奈伤痛
無奈伤痛 2021-01-27 01:27

I have something like this:

public static final String path;
static {
    path = loadProperties(\"config.conf\").getProperty(\"path\");
}

public static void mai         


        
6条回答
  •  逝去的感伤
    2021-01-27 02:17

    I'm accepting Peter Lawrey answer but post a complete example for anyone to use!

    I'm not going to use this in production code... there are other ways of doing it!

    public class Test {
    
        public static void main(String args[]) throws Exception {
            start();
            Thread.sleep(123);
            start();
        }
    
        private static void start() throws Exception {
    
            ClassLoader cl = new ClassLoader(null) {
                protected java.lang.Class findClass(String name) 
                throws ClassNotFoundException {
                    try{
                        String c = name.replace('.', File.separatorChar) +".class";
                        URL u = ClassLoader.getSystemResource(c);
                        String classPath = ((String) u.getFile()).substring(1);
                        File f = new File(classPath);
    
                        FileInputStream fis = new FileInputStream(f);
                        DataInputStream dis = new DataInputStream(fis);
    
                        byte buff[] = new byte[(int) f.length()];
                        dis.readFully(buff);
                        dis.close();
    
                        return defineClass(name, buff, 0, buff.length, null);
    
                    } catch(Exception e){
                        throw new ClassNotFoundException(e.getMessage(), e);
                    }
                }
            };
    
            Class t = cl.loadClass("Test$Restartable");
            Object[] args = new Object[] { new String[0] };
            t.getMethod("main", new String[0].getClass()).invoke(null, args);
        }
    
        public static class Restartable {
    
            private static final long argument = System.currentTimeMillis();
    
            public static void main(String args[]) throws Exception {
                System.out.println(argument);
            }
        }
    }
    

提交回复
热议问题