2017-08-19 31 views
0

我真的不確定我是否用正確的名稱來稱呼這些東西,所以很抱歉。在Java中通過字符串獲取類成員

我這有一個類文件:

class eSpecies { 
    protected String name; 
    protected String file; 
    protected int hp; 
    protected int atk; 
    protected int exp; 
    protected int type; 
    public int kill; 
    protected String flavour; 


    eSpecies(String name, String file, int hp,int atk, int exp, int type, int kill, String flavour){ 
     this.name=name; 
     this.file=file; 
     this.hp=hp; 
     this.atk=atk; 
     this.exp=exp; 
     this.type=type; 
     this.kill=kill; 
     this.flavour=flavour; 

    } 
} 

public class enemyDB{ 

    static eSpecies lsp  = new eSpecies("Lesser Shelled Pincher", "lsp", 500, 30, 50, 1, 0, "this is a small bug"); 
    static eSpecies gsp  = new eSpecies("Greater Shelled Pincher", "gsp", 50000, 50, 500, 1, 0, "this is a small bug"); 

} 

,並已參考它在另一個像這樣:

eSpecies e = enemyDB.lsp; 

我想知道如果有可能基本上做到這一點:

String type = "lsp"; 
eSpecies e = enemyDB.type; 

顯然,這是不行的,但我希望這個想法是明確enough-通過使用得到一個類對象字符串來獲取其名稱的一部分。謝謝!

+0

聽起來像一個地圖將做你想做的事情https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html –

+0

最後使用一張地圖,並得到它完美地工作 - 謝謝!! – Saiklex

回答

0

它被稱爲「反射」。從另一篇文章:

public void printFields(Object obj) throws Exception { 
    Class<?> objClass = obj.getClass(); 

    Field[] fields = objClass.getFields(); 
    for(Field field : fields) { 
     String name = field.getName(); 
     Object value = field.get(obj); 

     System.out.println(name + ": " + value.toString()); 
    } 
}  

但是,你應該避免它,如果可能的話。這不是很好的做法,因爲它破壞了像Java這樣的強類型語言的整個想法。

+0

謝謝f或者答案,但是,我無法思考如何將這個應用到我的代碼中(我確信我只是變得很厚) - 哪一部分是哪個?另外,如果這不是一種好的做法,還有什麼替代方案? – Saiklex

+0

調用printFields(enemyDB),它將打印該對象的所有字段,包括值。 – user1050755

0

反射可以成爲實現這一目標的方式。根據文檔:

如果基礎字段是靜態字段,obj參數將被忽略;它可能爲空。

此外,字段靜態應該是可見的。例如像公共領域。

公共靜態eSpecies LSP =新eSpecies(「小帶殼切兒」,...

需要你的代碼是通過名稱而迭代過場直接獲取,例如:

String type = "lsp"; 
eSpecies ep1 = (eSpecies) enemyDB.class.getField(type).get(null); 
+0

儘管它已經存在,但是當前正在獲取「未處理的異常:java.lang.NoSuchFieldException」。我已經公開了這個領域,不知道還有什麼可能是錯的? – Saiklex

+0

你在使用一些框架嗎? 你有沒有把他們嘗試捕捉內部..嘗試以此爲... 嘗試{ \t \t \t eSpecies EP1 =(eSpecies)enemyDB.class.getField(類型)獲得(NULL); \t \t \t System.out.println(ep1.name); \t \t \t \t } \t趕上(NoSuchFieldException E1){ \t \t \t E1。的printStackTrace(); \t \t} catch(SecurityException e1){ \t \t \t e1.printStackTrace(); \t \t} catch(IllegalArgumentException e1){ \t \t \t e1.printStackTrace(); \t \t} catch(IllegalAccessException e1){ \t \t \t e1.printStackTrace(); \t \t} –

+0

在Android Studio工作,所以我不認爲大部分的代碼工作...我不知所措 – Saiklex