Java 如何制作注释,将该类型的所有类添加到列表中
好的,我的一个程序有一种命令管理器。 有一个抽象的baceclass叫做Command,非常简单Java 如何制作注释,将该类型的所有类添加到列表中,java,list,class,annotations,Java,List,Class,Annotations,好的,我的一个程序有一种命令管理器。 有一个抽象的baceclass叫做Command,非常简单 public abstract class Command { protected String commandheader; protected int requiredlevel; protected Random rand; public Command(RANK rank,String command) { commandheader
public abstract class Command {
protected String commandheader;
protected int requiredlevel;
protected Random rand;
public Command(RANK rank,String command)
{
commandheader = command;
requiredlevel = rank.level;
}
}
然后在继承这个的每一个类中,我都有一些oop的魔力
public class MyCommand extends Command {
public MyCommand()
{
super(RANK.PLAYER,"blablabla");
}
}
然后,我还有一个命令助手类,它将这些命令保存在一个列表中,这样我就可以在传入命令时轻松找到该命令是否有效,以及获取所有可用命令的lsit
public class CommandHelper {
public enum RANK{
PLAYER(0);
public int level;
private RANK(int i)
{
level = i;
}
}
static List<Command> commandlist;
private static void initTheCommands()
{
//Add the commands to the list here.
commandlist.add(new MyCommand());
}
//Called by my main class
public static void Init()
{
if(commandlist == null)
{
//Were safe to initalise the stuff brah.
commandlist = new ArrayList<Command>();
initTheCommands();
for(Command cmd : commandlist)
{
System.out.println("Loaded command: " + cmd.commandheader);
}
System.out.println("[INFO] Initalised the command helper");
}
else
{
System.out.println("[INFO] Command list is already populated.");
}
}
}
公共类CommandHelper{
公共枚举等级{
运动员(0);
公共智力水平;
私人职级(国际一级)
{
级别=i;
}
}
静态列表命令列表;
命令()中的私有静态void
{
//将命令添加到此处的列表中。
添加(新的MyCommand());
}
//我的主班叫我
公共静态void Init()
{
if(commandlist==null)
{
//我们可以安全地初始化这些东西,布拉。
commandlist=newarraylist();
初始化命令();
for(命令cmd:commandlist)
{
System.out.println(“加载的命令:“+cmd.commandheader”);
}
System.out.println(“[INFO]初始化了命令助手”);
}
其他的
{
System.out.println(“[INFO]命令列表已填充。”);
}
}
}
到目前为止,这个系统工作完全正常。但是它有一个缺陷,对于我或其他编辑器添加的每个命令,我们必须手动将其添加到列表中,这看起来很乏味,并且在同步文件时可能会导致问题。所以我想知道,是否有任何方法可以将每个命令添加到列表中,而不必手动将其放在列表中?也许是注释我的方法,或者只是将其添加到列表中?我看到了一些关于反思的东西,但我不认为这正是我想要的,尽管我不确定。我以前从未使用过,也没有做过注释,所以我不确定这是否可信。如果这是你真正想做的,你可以做这样的事情 声明您的注释
@Target (ElementType.TYPE)
@Retention (RetentionPolicy.RUNTIME)
public @interface CommandAnnotation {
}
为命令添加注释
@CommandAnnotation
public class MyCommand {
然后检查他们,像这样的
...
import org.reflections.Reflections;
...
public void loadCommands() {
Reflections reflections = new Reflections("com.my.package");
Set<Class<?>> allClasses = reflections.getSubTypesOf(Command.class);
for (Class<?> outerClazz : allClasses) {
CommandAnnotation annotation = outerClazz.getAnnotation(CommandAnnotation.class);
if (annotation == null)
continue;
。。。
导入org.reflections.reflections;
...
公共void loadCommands(){
反思=新反思(“com.my.package”);
SetOk,所以我试着添加它,它到底是如何被放入列表的?commandlist.add(outerClazz);?不知道。我很抱歉。我以为你可以上网并且渴望学习。你可能想用谷歌搜索你能用类对象做什么。仍然不能正确地获取它。我不擅长类型。