Java 在ja中创建一个JAR文件
我已经创建了一个名为CustomValidations.jar的jar文件,其中包含一个名为CustomValidation.java的类文件Java 在ja中创建一个JAR文件,java,jar,Java,Jar,我已经创建了一个名为CustomValidations.jar的jar文件,其中包含一个名为CustomValidation.java的类文件 package validation; public class CustomValidation { public boolean matchFields(String str1,String str2){ if (!str1.equals(str2)) { return fal
package validation;
public class CustomValidation {
public boolean matchFields(String str1,String str2){
if (!str1.equals(str2)) {
return false;
}
else {
return true;
}
}
}
我创建了另一个简单的java项目,需要调用matchFields方法
package com.codes;
import CustomValidation.*;
public class TestClass {
public boolean CheckEmail(){
if(matchFields("sowmya","sowmya")){
System.out.println("Matched");
}
else {
System.out.println("Not Matched");
}
}
}
它向我抛出一个错误,说“导入CustomValidation无法解决”
调用方法的正确方法是什么?
matchFields
不是静态的,您需要一个CustomValidation
的实例才能使用它。重要语句也有点错误,通常是import{package path}.{class name}
或者在您的示例中是import validation.CustomValidation
(甚至是import validation.
)
您可以将该方法设置为静态
public class CustomValidation {
public static boolean matchFields(String str1,String str2){
if (!str1.equals(str2)) {
return false;
}
else {
return true;
}
}
}
然后执行静态导入
import static validation.CustomValidation.matchFields;
public class TestClass {
public boolean CheckEmail(){
if(matchFields("sowmya","sowmya")){
System.out.println("Matched");
}
else {
System.out.println("Not Matched");
}
}
}
这一切都假设当构建并运行TestClass
时,包含CustomValidation
的jar文件在类路径中可用
而不是
import CustomValidation.*;
应该是
import validation.*;
而且该方法不是静态的,所以您需要创建实例来访问该方法。作为:
new CustomValidation().matchFields("sowmya","sowmya");
您必须将此项目作为依赖项添加到您正在使用该代码的项目中。matchFields
不是静态的,您需要一个CustomValidation
的实例才能使用它…我已经在构建路径中添加了此jar文件。。还需要其他什么吗“CustomValidation.java”,我想您已经在jar中添加了源文件。请添加“CustomValidation.class”“相反,我尝试了上述更改,但仍然在此行获得了错误多个标记-无法解析导入验证-无法解析导入验证。无法解析CustomValidation…..方法匹配字段(字符串,字符串)对于类型testclasss,它是未定义的。听起来,Jar或者不包含该类,或者您没有在项目的类路径中包含该Jar。尝试提取Jar文件的内容,并确保它在类包声明所代表的目录中包含您期望的类。天哪……在创建Jar文件时,我没有包括“导出生成的类文件和资源”选项……它工作正常…………谢谢@MadProgrammer
new CustomValidation().matchFields("sowmya","sowmya");