java - 使用URLClassLoader加载类,不会报错,但被加载类中的内容也没有打印出来
黄舟
黄舟 2017-04-18 09:17:30
0
1
428

被加载类和加载类的程序在一个文件夹下;
运行没有任何结果:


D:java_exercise>javac URLTest.java

D:java_exercise>java URLTest

D:java_exercise>


加载类:

import java.net.*;
import java.io.File;
import java.net.URLClassLoader ;
public class URLTest
{
        public static void main (String [ ] args )
        {
                URL[ ] urls = new URL[1] ;
                try {
                        urls[0] = new URL("file",null,(new File(System.getProperty("user.dir") + File.separator)).toString ( ) );
                        URLClassLoader cl = new URLClassLoader ( urls) ;
                        cl.loadClass ("Testee");
                }
                catch (Exception e)
                {
                        e.printStackTrace ( ) ;
                }
        }
}

被加载类:

public class Testee
{
        static
        {
                System.out.println ("I am loaded!");
        }
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
Ty80

The problem lies in when the static code block of the class is executed:

在类初始第一个实例的时候或者静态方法被使用之类的(或者其他:??具体看Java官方的语言细究吧)

You have just loaded the class and it does not meet the conditions

            urls[0] = new URL("file", null, (new File(System.getProperty("user.dir") + File.separator)).toString());
            URLClassLoader cl = new URLClassLoader(urls);
            Class<?> testee = cl.loadClass("Testee");
            Constructor<?> constructor = testee.getConstructor();
            Object beanObj = constructor.newInstance();
            

That’s it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!