IT story

Java에서 변수 유형을 어떻게 알 수 있습니까?

hot-time 2020. 7. 7. 07:33
반응형

Java에서 변수 유형을 어떻게 알 수 있습니까?


변수를 선언한다고 가정 해 봅시다.

String a = "test";

그리고 나는 그것이 어떤 유형인지 알고 싶습니다. 즉, 출력은 java.lang.String어떻게해야합니까?


a.getClass().getName()

이름을 원하면 Martin의 방법을 사용하십시오. 특정 클래스의 인스턴스인지 알고 싶다면 :

boolean b = a instanceof String


검색 엔진에서 배웠습니다 (영어는 매우 나쁩니다. 그래서 코드 ...) 업 :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

이 방법 :

str.getClass().getSimpleName();
value:String

이제 예 :

Object o = 1;
o.getClass().getSimpleName();
value:Integer

나는 거기에 Martin의 대답을 확장하고 싶습니다 ...

어떤 "변수 유형이"그런 식으로 인쇄 할 수 있도록 그의 해결책은 오히려 좋은이지만, 불통 될 수있다. (그것은, 실제로 값 유형의 더 많은 주제에 ). 즉, "비틀어 짐"은 이에 대한 강력한 단어 일 수 있습니다. 어쨌든 도움이 될 수 있습니다.

마틴 솔루션 :

a.getClass().getName()

그러나 무엇이든 작동하려면 다음을 수행하십시오.

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

이 경우, 기본 요소는 랩퍼로 랩핑됩니다. 이 경우 기본 객체를 얻을 수 있습니다.

나는 이것을 다음과 같이 사용했다.

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

제네릭 사용하기 :

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

Java의 연산자 오버로드 기능 사용

class Test {

    void printType(String x) {
        System.out.print("String");
    }

    void printType(int x) {     
        System.out.print("Int");
    }

    // same goes on with boolean,double,float,object ...

}

변수가 클래스 속성이 아닌 한 Joachim Sauer가 말한 것에 동의하지 않습니다 (변수 유형! 값 유형이 아닙니다!). (클래스 필드를 검색하고 이름으로 올바른 필드를 가져와야합니다 ...)

실제로 나를 a.xxx().yyy()위해이 메서드를 호출하는 컨텍스트에 따라 정확히 동일한 객체에서 답변이 다르기 때문에 모든 메서드가 올바른 답변을 제공 하는 것은 완전히 불가능합니다 ...

teehoo가 말했듯이, 테스트 할 정의 된 유형 목록을 컴파일하면 instanceof를 사용할 수 있지만 서브 클래스가 true를 반환하게됩니다 ...

One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field and create your own Field class, and then declare all your local variables as this custom Field implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?


I think we have multiple solutions here:

  • instance of could be a solution.

Why? In Java every class is inherited from the Object class itself. So if you have a variable and you would like to know its type. You can use

  • System.out.println(((Object)f).getClass().getName());

or

  • Integer.class.isInstance(1985); // gives true

or

  • isPrimitive()

    public static void main(String[] args) {
    
     ClassDemo classOne = new ClassDemo();
     Class classOneClass = classOne();
    
     int i = 5;
     Class iClass = int.class;
    
     // checking for primitive type
     boolean retval1 = classOneClass.isPrimitive();
     System.out.println("classOneClass is primitive type? = " + retval1);
    
     // checking for primitive type?
     boolean retval2 = iClass.isPrimitive();
     System.out.println("iClass is primitive type? = " + retval2);
    }
    

This going to give us:

  1. FALSE
  2. TRUE

Find out more here: How to determine the primitive type of a primitive variable?

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

http://docs.oracle.com/cd/E26806_01/wlp.1034/e14255/com/bea/p13n/expression/operator/Instanceof.html

참고URL : https://stackoverflow.com/questions/2674554/how-do-you-know-a-variable-type-in-java

반응형