gpt4 book ai didi

java - 使用 Java 注解消除重复

转载 作者:行者123 更新时间:2023-12-01 14:19:39 25 4
gpt4 key购买 nike

是否可以使用注释使以下代码更清晰、更少重复?我知道 java 8 闭包是可能的,但试图在 java 6/7 上运行它

Variable x = new Variable(this,"HClass","HC"){
@Override
String getValue(Player p){
return getHeroFromPlayer(p).getHeroClass().getName();
}
};

Variable y = new Variable(this,"HSecClass","HSC"){
@Override
String getValue(Player p){
return getHeroFromPlayer(p).getSecondClass().getName();
}
};

Variable z = new Variable(this,"HLevel","HL"){
@Override
String getValue(Player p){
return getHeroFromPlayer(p).getLevel();
}
};

Variable a = new Variable(this,"HMastered","HMa"){
@Override
String getValue(Player p){
return getHeroFromPlayer(p).isMaster(getHeroFromPlayer(p).getHeroClass()) && (heroSClass == null || getHeroFromPlayer(p).isMaster(heroSClass))
? LocaleType.MESSAGE_HEROES_TRUE.getVal() : LocaleType.MESSAGE_HEROES_FALSE.getVal();;
}
};

这会持续一段时间,其中它们都被添加到 map 中, map 会延迟返回结果。

<小时/>

编辑:我希望注释能让我做一些类似的事情

@Variable("HLevel","HL")
String getHLevel(){getHeroFromPlayer(p).getlevel();}
<小时/>

编辑: Variable.java

abstract class Variable {
final private VariableGroup vg;
final private List<String> keys = new Vector<String>();

Variable(VariableGroup vg,String...varargs){
this.vg = vg;
for (String s:varargs){
keys.add(s);
}
}


abstract String getValue(Player p);

}

最佳答案

根据您的评论,您可以执行类似的操作

@Variable("Primary Class")
public String getHClass(Player p) {
return getHeroFromPlayer(p).getHeroClass().getName();
}

@Variable("Primary Class Level")
public int getHLevel(Player p) {
return getHeroFromPlayer(p).getHLevel();
}

@Variable("Secondary Class")
public String getHSecClass(Player p) {
return getHeroFromPlayer(p).getSecondClass().getName();
}

@Variable("Secondary Class Level")
public int getHLevel(Player p) {
return getHeroFromPlayer(p).getHSecLevel();
}

注意:不需要所有字段都返回字符串。要获取此信息,您可以执行以下操作

Class heroClass = 
for(Method method : heroClass.getMethods()) {
Variable var = method.getAnnotation(Variable.class);
if (var == null) continue; // ignore Object.getClass()
String description = var.value; // text to display to users
String attributeName = method.getName().substring(3); // cut "get"
String initials = attributeName.replaceAll("[a-z]+", "");

}

关于java - 使用 Java 注解消除重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730695/

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