繁体   English   中英

使用String在java中查找Class?

[英]Using String to find Class in java?

我制作了一个名为 Entity 的 class,并具有以下代码:

Entity zombie1 = new Entity();

我从扫描仪获取输入“僵尸”,然后根据末尾的级别连接一个数字,将“zombie1”作为字符串......我希望能够使用该字符串并调用

zombie1.shoot("shotgun");

但我似乎找不到解决方案。 我只想做一个 if 语句,但我希望能够创建尽可能多的僵尸,而不必每次都放入更多的 if 语句。

我已经阅读了使用反射和 forString 的文章,但这似乎不是我想要的。

你能帮忙的话,我会很高兴。

可能的解决方案是使用Map<String, Entity>来存储和检索基于特定字符串的实体。 如果您的实体子类型数量有限,例如僵尸、吸血鬼、受害者等,您可以拥有一个Map<String, List<Entity>> ,允许您将字符串 map 到特定类型的实体,然后按数字获取该类型。

例如,

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Foo002 {
   private static final String ZOMBIE = "zombie";

   public static void main(String[] args) {
      Map<String, List<Entity>> entityMap = new HashMap<String, List<Entity>>();

      entityMap.put(ZOMBIE, new ArrayList<Entity>());

      entityMap.get(ZOMBIE).add(new Entity(ZOMBIE, "John"));
      entityMap.get(ZOMBIE).add(new Entity(ZOMBIE, "Fred"));
      entityMap.get(ZOMBIE).add(new Entity(ZOMBIE, "Bill"));

      for (Entity entity : entityMap.get(ZOMBIE)) {
         System.out.println(entity);
      }
   }
}

class Entity {
   private String type;
   private String name;

   public Entity(String type, String name) {
      this.type = type;
      this.name = name;
   }

   public String getType() {
      return type;
   }

   public String getName() {
      return name;
   }

   @Override
   public String toString() {
      return type + ": " + name;
   }

}

这不是你最好的选择。 您最好的选择是拥有 Map;

// PLEASE LOOK INTO WHICH MAP WOULD BE BEST FOR YOUR CASE OVERALL
// HASHMAP IS JUST AN EXAMPLE.
Map<String, Entity> zombieHoard = new HashMap<String, Entity>;

String getZombieID( int id )
{
    return String.format( "zombie%s", id );
}
String createZombie() {
    String zid = getZombieID( Map.size() );
    Map.put( zid, new Entity() );
    return zid;
}

void sendForthTheHoard() {
   createZombie();
   createZombie();
   String currentZombie = createZombie();
   zombieHoard.get( currentZombie ).shoot( "blow-dryer" );
   zombieHoard.get( getZombieID( 1 ) ).eatBrains();
}

将您的僵尸放入 ArrayList。 例子:

ArrayList<Entity> zombies = new ArrayList<Entity>();
Entity zombie1 = new Entity();
zombies.add(zombie1);
Entity zombie2 = new Entity();
zombies.add(zombie2);
etc...

然后是时候调用某个僵尸到以下:

zombies.get(1).shoot("shotgun");

如果您正在谈论在 object 上动态调用方法,则可以使用反射来获取方法 object 并调用它(注意:我可能无意中在此 Java 中混淆了一些 ZD7EFA19FBE7D3972FD5ADB6024223D74 语法):

Entity zombie1 = new Entity();
Method shootMethod = Entity.class.getMethod("shoot", new Class[] { string.class });
shootMethod.invoke(zombie1, new Object[] { "shotgun" });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM