gpt4 book ai didi

java - 注释方法以便稍后选择它们

转载 作者:行者123 更新时间:2023-11-29 06:05:59 25 4
gpt4 key购买 nike

是否有可能以某种方式注释 Java 方法,以便我以后可以给另一个方法一个字段标识符或类似的东西,以便该方法可以调用正确的方法?

我知道通常你会用接口(interface)来做到这一点,但在我的例子中,这将是一个巨大的接口(interface)......我需要在我的数据库的实体类中使用它(并且我不允许使用ORM 映射器)

例如:我有实体

public class Account{
private String username;
private String password;
private String name;
private String mail;


public void setUserName(String username){
this.username = username;
}

public String getUserName(){
return username;
}

[all other getter/Setter...]
}

现在我想告诉一个方法它需要验证一个字段,例如 username 字段。

执行的方法应该如下所示:

public void validateField(XXX Field, Entity entity) throws ValidationFailedException, EmptyFieldException;

其中 XXX 是 FieldIdentifier。

这在 Java 中有任何可能吗?

我唯一的猜测是我在其中使用了 public static final ìnt 东西来为每个字段提供一个 Method 左右...

最佳答案

你用什么?我没有看到任何可以从中猜出您的框架的注释。如果您使用 Hibernate,您可以使用类似 @NotNull 或其他的东西,甚至可以进行自定义验证:这就是你的例子:

public class Account{

@NotNull(message="This field should not be null")
private String username;
@NotBlank(message="This string should not be empty or null")
private String password;
private String name;
private String mail;


public void setUserName(String username){
this.username = username;
}

public String getUserName(){
return username;
}

[all other getter/Setter...]
}

http://silentwalker.wordpress.com/2009/04/07/custom-validation-in-hibernate/

您还可以在不使用任何框架的情况下创建自己的注释,并使用它们 @prepersist 或其他任何东西。基本上天空是极限。

P.S 由于您不想使用任何非内部代码,因此您可以采用以下方法:

首先,你可以定义一个注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotNull{
public String message() default "";
}

然后,在持久化该类之前,您将检查它的字段:

所以,你有这样的事情:

Field[] classFields = yourObjectPrePersist.getClass().getDeclaredFields();
for (int i = 0; i < classFields.length; i++) {
classFields[i].setAccessible(true);//take notice that if you use a SecurityManager, you should work around it
if (classFields[i].getAnnotation(NotNull.class) != null) {
Object value = classFields[i].get(yourObjectPrePersist);
//here check if value is null or not and then return the message
if (value == null) {
throw new SomeException(((NotNull) classFields[i].getAnnotation(NotNull.class)).message());
}
}
}

关于java - 注释方法以便稍后选择它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8525746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com