Java:“CustomClass1”之间的区别和“CustomClass1.class”? [英] Java: difference between "CustomClass1" and "CustomClass1.class"?

查看:663
本文介绍了Java:“CustomClass1”之间的区别和“CustomClass1.class”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是继续 Java:使用类作为一个值在HashMap



以下两种方法有什么区别?:

1)

 字符串名称=(

CustomClass1
)obj1
).getName ();



<2>和2)

 字符串名称=(

mapQuery2ResponseType.get(string1)
)obj1
).getName();

其中, mapQuery2ResponseType.get(string1)返回值类型 Class <?>



第一种方法完美地工作,但在第二种方法中,错误说对令牌obj1的语法错误,删除此令牌



如何修改第二种方法(使用Map)以便在第一种情况下工作?



如何使 mapQuery2ResponseType.get(string1 )返回 CustomClass1 而不是 CustomClass1.class

$ b $对于编译器来说,Cast是一条指令,你不能等到运行时才找出你将要投入的Class。编译器没有办法知道当你调用它时是否会出现一个getName()方法。



你需要在编译时加入一个通用的超类型的地图共享的所有内容,让你确信它们都有一个'getName()'方法。如果这是不可能的,那么你就进入了反思的世界,对方法进行修改,以便可以调用它。



这个问题解答了如何调用 getName方法,当你在编译时不知道该类时,可以使用任何对象:
在给方法名字作为字符串时,如何调用Java方法?



如果你的方法确实是实际的bean属性getter和setter,你也可以使用 apache BeanUtils库从对象获取命名属性的值。


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?

解决方案

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.

这篇关于Java:“CustomClass1”之间的区别和“CustomClass1.class”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆