Is it possible to get the type of an unknown variable in Java?

Is it possible to get the type of a variable declared (but not instantiated) in Java? eg:

public class Foo {

     FooTwo foo2;
     FooTwo foo3;
     FooThree foo4;

     public static void main(String[] args) {
         if (foo2.getClass() == foo3.getClass()) {
             System.out.println("foo2 is the same type as foo3");
         }
         if (foo3.getClass() == foo4.getClass()) {
             System.out.println("foo3 is the same class as foo4");
         }
     }
}

With an exit:

foo2 is the same type as foo3

obviously, the method getClass()does not work with an immutable variable, so this code does not work. I assume that the information I'm looking for is stored somewhere in a variable (pointer?) For type safety and that it may be available. Can this comparison be achieved?

: . , , ArrayList . , ( ) , arraylist , , ( ).

: . .

+4
2

. , , :

List<String> list = new ArrayList<String>();
System.out.println(list.getClass());

class java.util.ArrayList, java.util.List<java.lang.String>, getClass() , list, list.

getClass() , .


, ( ) , [& hellip;] ( ).

Java - , , . , :

public void doNothing(Object obj) {
    obj = "obj";
}

. obj, , , "obj"; , obj . , .

; type Field, , .

+6

- , . . , , .

import java.lang.reflect.Field;

public class Foo {

    static FooTwo foo2;
    static FooTwo foo3;
    static FooThree foo4;

    public static void main(String[] args)  {

        try {
            Field foo2Field = Foo.class.getDeclaredField("foo2");
            Field foo3Field = Foo.class.getDeclaredField("foo3");
            Field foo4Field = Foo.class.getDeclaredField("foo4");

            if (foo2Field.getType().equals(foo2Field.getType())) {
                System.out.println("foo2 is the same type as foo3");
            }
            if (foo3Field.getType().equals(foo4Field.getType())) {
                System.out.println("foo3 is the same class as foo4");
            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            // TODO handle this if this can happen
        } catch (SecurityException e) {
            e.printStackTrace();
            // TODO handle this appropriately
        }

    }

}

class FooTwo {

}

class FooThree {

}
+2

All Articles