2013-12-12 7 views
0

그래서 클래스가 테스트 불렀다 : 당신이 볼 수 있듯이자바, 클래스의 모든 변수 값을 얻을

public class Test{ 
    protected String name = "boy"; 
    protected String mainAttack = "one"; 
    protected String secAttack = "two"; 
    protected String mainType"three"; 
    protected String typeSpeak = "no spoken word in super class"; 

//Somehow put all the class variables in an Array of some sort 
    String[] allStrings = ??(all class' strings); 
//(and if you feel challenged, put in ArrayList without type declared. 
//So I could put in, not only Strings, but also ints etc.) 

    public void Tester(){ 
    //Somehow loop through array(list) and print values (for-loop?) 
    } 
} 

, 나는 배열이나 ArrayList를 (또는 비슷한) 모든 클래스 변수를 넣을 자동으로 그리고 나서 배열을 반복하고 값을 인쇄/가져올 수 있기를 원합니다. 향상된 루프를 사용하는 것이 바람직합니다.

+0

getters와 setters를 사용하십시오. –

+0

왜 배열을 사용하여 시작하지 않으시겠습니까? 왜 별도의 변수가 필요한가요? –

+0

이것은 끔찍한 생각입니다. 이런 식으로 수업을 설계하지 마십시오. 성찰을 시험하기 위해서라면 괜찮아. '반사 '가 핵심 단어입니다. –

답변

0

정말 필요한 경우 리플렉션을 사용해야합니다.

그러나 Map (아마도 HashMap)에 값을 저장 한 다음이를 쉽게 쿼리/설정/등 할 수있는 훨씬 더 나은 방법이 있습니다.

0

Array 또는 Arraylist

HashMap 대신 변수와 그 값을 저장 또는 MapHashmap를 사용하여 목적하는 쌍으로 저장 "키/값"둘. 이 기사에서는 HashMap 인스턴스를 생성하고 HashMap 데이터를 반복하는 방법을 설명한다.

+0

나는 알고있다, 그리고 너는 옳다. 하지만 그건 내 경우에 내가 찾고있는 것이 아니야 ... – Ken

0

값에 HashMap을 사용하고 반복하지 않는 이유는 무엇입니까?

Iterate through a HashMap

+0

나는 이해하고, 당신은 옳다. 하지만 그건 내 문제에 지금 적용되지 않습니다 ... – Ken

0

는이 작업을 수행합니다.

String threeEleves = "sky"; 
String sevenDwarves = "stone"; 
String nineMortal = "die"; 
String oneRing[] = new String[] // <<< This 
{ 
    threeElves, 
    sevenDwarves, 
    nineMortal 
} 

또는 다른 말했듯이

// in some class. 
public void process(final String... varArgs) 
{ 
    for (String current : varArgs) 
    { 
    } 
} 

String one = "noodles"; 
String two = "get"; 
String three = "in"; 
String four = "my"; 
String five = "belly"; 

process (one, two, three, four, five); 
0

을, 이러지 마. 그러나 이것은 다음과 같습니다.

Class<?> cl = this.getClass(); 
List<Object> allObjects = new ArrayList<Object>(); 
for (java.lang.reflect.Field f: cl.getDeclaredFields()) 
{ 
    f.setAccessible(true); 
    try 
    { 
     Object o = f.get(this); 
     allObjects.add(o); 
    } 
    catch (Exception e) 
    { 
     ... 
    } 
} 
for (Object o: allObjects) 
    System.out.println(o); 
+0

나는 이것을 시도했지만 작동하지 않습니다 ... 좋은 코드 – Ken

+0

그래도 잘 작동합니다. 작동하지 않는 것을 제게 말할 수 있습니까? 대부분의 경우 setAccessible이 중요합니다. – geert3

관련 문제