Java: difference between “CustomClass1” and “CustomClass1.class”?

吃可爱长大的小学妹 提交于 2019-12-25 18:21:31

问题


This question is in continuation with Java: Using Classes as a value in hashmap.

What is the difference between following two approaches?:

1)

String name = (
                  (
                       CustomClass1
                  )obj1
              ).getName();

and 2)

String name = (
                  (
                       mapQuery2ResponseType.get("string1")
                  )obj1
              ).getName();

where, mapQuery2ResponseType.get("string1") return value of type Class<?>

First approach works perfectly but in second approach it's giving an error saying Syntax error on token "obj1", delete this token.

How can I modify second approach (Using Map) so as to work as in first case?

How can I make mapQuery2ResponseType.get("string1") to return CustomClass1 instead of CustomClass1.class?


回答1:


A Cast is an instruction to the compiler, you can't wait until runtime to find out what Class you're going to cast to! There is no way for the compiler to know whether or not whatever comes out of that map when you call it is actually going to have a getName() method on it or not.

You'll need to put in a cast at compile time to some common supertype all of the contents of the map share that makes you confident they all have a 'getName()' method. If that's not possible you're off into the world of reflection to fine the method so that you can call it.

Here is a question that answers how to call a "getName" method on any arbitrary object when you don't know the class at compile time: How do I invoke a Java method when given the method name as a string?

If your methods are indeed actual bean property getters and setters, you could also use the apache BeanUtils library to get the values of named properties from an object.




回答2:


How can I make mapQuery2ResponseType.get("string1") to return CustomClass1 instead of CustomClass1.class?

You can't. A Java type cast requires a class/type that is known at compile time.

You should be able to do what your second example seems to be trying to do as follows.:

1) Declare an interface:

    public interface Named {
        String getName();
    }

2) Change all of the classes in the request type map to implements Named.

3) Change the "second approach" code above to:

    String name = ((Named) obj1).getName();

The other alternative would be to use reflection to lookup the getName() method on obj1.getClass(), and then use method.invoke(...) to call it.



来源:https://stackoverflow.com/questions/15583978/java-difference-between-customclass1-and-customclass1-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!