You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java项目运行报java.lang.NoSuchMethodError错误,寻求解决方案

解决Java中NoSuchMethodError针对带参构造方法的问题

你的代码逻辑本身是正确的,出现java.lang.NoSuchMethodError: OOPS.constructors.Student.(Ljava/lang/String;I)V错误,本质是运行时找不到你定义的带参构造方法,大概率是编译与运行的字节码不一致导致的,以下是具体解决步骤:

你的代码:

package OOPS.constructors;

class Student{
   String name;
   int age;

    public void printInfo(){
        System.out.println(this.name);
        System.out.println(this.age);
    };

    Student(String name,int age){
        this.name = name;
        this.age = age;
    }
}

public class Parameterized{
    public static void main(String[] args) {
     Student s2 = new Student("yash", 21);
     s2.printInfo();   
    }
}

错误信息:

Exception in thread "main" java.lang.NoSuchMethodError: OOPS.constructors.Student.(Ljava/lang/String;I)V
at OOPS.constructors.Parameterized.main(Parameterized.java:20)

解决方法:

  • 清理旧编译文件,重新编译:删除项目中生成的bin或target目录下的.class字节码文件,确保编译生成的是最新的类文件
  • IDE环境操作:如果你用IDEA、Eclipse这类IDE,执行Clean Project + Rebuild Project,清除IDE缓存的旧编译结果
  • 手动编译注意事项:用命令行编译时,要一次性编译所有相关类,比如执行javac OOPS/constructors/*.java,再用java OOPS.constructors.Parameterized运行,避免只编译主类而没更新Student类的字节码
  • 检查类路径:确保运行时的类路径里没有包含旧版本的Student类字节码,避免加载了错误的类文件

内容的提问来源于stack exchange,提问作者Yash Darole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:50:14