簡體   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