我创建了一个名为CustomValidations.jar的jar文件,其中包含一个名为CustomValidation.java的类文件
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” 调用方法的正确方法是什么?
答案 0 :(得分:1)
导入错误
而不是
import CustomValidation.*;
应该是
import validation.*;
并且方法也不是静态的,因此您需要创建Instance来访问该方法。为:
new CustomValidation().matchFields("sowmya","sowmya");
答案 1 :(得分:0)
matchFields
不是静态的,您需要CustomValidation
的实例才能使用它。重要的陈述也有点错误,通常是import {package path}.{class name}
或在您的情况下import validation.CustomValidation
(甚至是import validation.*
)
import validation.CustomValidation;
public class TestClass {
public boolean CheckEmail(){
CustomValidation customValidation = new CustomValidation();
if(customValidation.matchFields("sowmya","sowmya")){
System.out.println("Matched");
}
else {
System.out.println("Not Matched");
}
}
}
您可以制作方法static
public class CustomValidation {
public static boolean matchFields(String str1,String str2){
if (!str1.equals(str2)) {
return false;
}
else {
return true;
}
}
}
然后执行static
导入
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");
}
}
}
这一切都假定在CustomValidation
构建并运行时,类路径中包含TestClass
的jar文件