weixin_44649811
木头和马尾的马尾
2021-01-15 15:12

在程序里动态生成一个类文件再加载,找不到

  • java

public class text {

    public static void main(String[] args) throws ClassNotFoundException, IOException {
        String str = "package date20200321.sorm.utils;\n" +
                "\n" +
                "/**\n" +
                " * @description:\n" +
                " * @Author: YaoDong\n" +
                " * @Date: 2021/1/15 2:45 下午\n" +
                " */\n" +
                "public class t {\n" +
                "    private int age;\n" +
                "\n" +
                "    static {\n" +
                "        System.out.println(\"t-----------\");\n" +
                "\n" +
                "    }"
                +
                "    public t(int age) {\n" +
                "        this.age = age;\n" +
                "    }\n" +
                "\n" +
                "    public int getAge() {\n" +
                "        return age;\n" +
                "    }\n" +
                "\n" +
                "    public void setAge(int age) {\n" +
                "        this.age = age;\n" +
                "    }\n" +
                "}\n";


        File file = new File("/Users/huxiao/Documents/yaodong/JAVA-myself-code/java-learning/src/date20200321/sorm/utils/t.java");
        if (!file.exists()) {
            file.createNewFile();

        }
        System.out.println("纯在:" + file.exists());
        BufferedWriter writer=null;
        writer = new BufferedWriter(new FileWriter(file));
        writer.write(str);
        writer.flush();
        writer.close();

        Class c=Class.forName("date20200321.sorm.utils.t");
    }
}
如上所示,在text立面生成一个t.java的类,然后再继续加载这个类。但显示找不到这个类。如果先生成,再在另一个程序里加载是可以的。
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

5条回答