Java 在验证时标识从同一抽象类生成的类类型

Java 在验证时标识从同一抽象类生成的类类型,java,validation,abstract-class,Java,Validation,Abstract Class,我有一个名为Company的抽象类,它有一些属性。通过扩展此抽象类创建的两种不同类型的类。我必须在抽象类中添加自定义验证。当请求到来时,我必须确定类的类型。我使用了“的实例”来检查类型,但它没有按预期工作。我怎么检查 @UniqueCode(columnName = "companyCode") public abstract class Company { private String companyCode; private String companyName; // some other

我有一个名为Company的抽象类,它有一些属性。通过扩展此抽象类创建的两种不同类型的类。我必须在抽象类中添加自定义验证。当请求到来时,我必须确定类的类型。我使用了“的实例”来检查类型,但它没有按预期工作。我怎么检查

@UniqueCode(columnName = "companyCode")
public abstract class Company {
private String companyCode;
private String companyName;
// some other code
}

public class PsiCompany extends Company {
  private Long id;
}

public class IndentAgent extends Company {
  private Long id;
  private String cbRegNo;
}

public class UniqueCodeValidator implements ConstraintValidator<UniqueCode, Object> {

  @Override
  public void initialize(UniqueCode constraintAnnotation) {}

  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {

     /*
     * How do I know the class type from object ?
     */
  }
}
@UniqueCode(columnName=“companyCode”)
公开抽象类公司{
私有字符串公司代码;
私有字符串companyName;
//其他代码
}
公营公司扩展公司{
私人长id;
}
公共类代理扩展公司{
私人长id;
私有字符串cbRegNo;
}
公共类UniqueCodeValidator实现ConstraintValidator{
@凌驾
public void initialize(UniqueCode constraintanotation){}
@凌驾
公共布尔值有效(对象值、ConstraintValidatorContext上下文){
/*
*如何从对象中知道类类型?
*/
}
}
无论何时发送IndentAgent对象,它都可以正常工作,但如果发送公司对象,它也会进入IndentAgent代码块。如何从isValid()方法中的对象中识别类类型?

这是有效的:

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    if (value instanceof PsiCompany) {
        System.out.println("PsiCompany");
        // do your thing
    } else if (value instanceof IndentAgent) {
        System.out.println("IndentAgent");
        // do your other thing
    }
    // return bool
}

尝试使用
IndentAgent.class.isInstance(value)
作为您的if条件
if(IndentAgent的值实例){…}否则(PsiCompany的值实例){…}
无效Java@ShreyGarg为什么
IndentAgent.class.isInstance(value)
比这里的
IndentAgent的值实例
工作得更好呢?@Andrew,我知道IndentAgent的值实例不起作用。获取类类型的最佳方法是什么?
IndentAgent的值实例
PsiCompany的值实例
应该可以工作吗?你能告诉我你是如何使用那些失败的代码的吗?这是行不通的。我一开始是这么做的。但当发送PsiCompany对象时,无法区分PsiCompany和IndentAgent类,因为它们都具有id属性。请重试,它应该可以工作。我刚才试过,只是想再检查一下