Groovy def 和 Java Object 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3937271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between Groovy def and Java Object?
提问by Without Me It Just Aweso
I'm trying to figure out the difference between
我试图找出两者之间的区别
Groovy:
常规:
def name = "stephanie"
Java:
爪哇:
Object name = "stephanie"
as both seem to act as objects in that to interact with them i have to cast them to their original intended type.
由于两者似乎都充当与它们交互的对象,因此我必须将它们转换为原始预期类型。
I was originally on a search for a java equivalent of C#'s dynamic class ( Java equivalent to C# dynamic class type?) and it was suggested to look at Groovy's def
我最初是在搜索 C# 动态类的Java 等效项(Java 等效于 C# 动态类类型?),有人建议查看 Groovy 的def
for example my impression of groovy's def is that I could do the following:
例如,我对 groovy 的 def 的印象是我可以执行以下操作:
def DOB = new Date(1998,5,23);
int x = DOB.getYear();
however this wont build
但是这不会建立
thanks,steph
谢谢,斯蒂芬
Solution edit: Turns out the mistake iw as making is I had a groovy class wtih public properties (in my example above DOB) defined with def but then was attemping to access them from a .java class(in my example above calling .getYear() on it). Its a rookie mistake but the problem is once the object leaves a Groovy file it is simply treated as a Object. Thanks for all your help!
解决方案编辑:原来我犯的错误是我有一个带有公共属性的 groovy 类(在我上面的 DOB 示例中)用 def 定义,但随后试图从 .java 类访问它们(在我上面的示例中调用 .getYear( ) 在上面)。这是一个新手错误,但问题是一旦对象离开 Groovy 文件,它就会被简单地视为对象。感谢你的帮助!
回答by Erich Kitzmueller
Per se, there is not much difference between those two statements; but since Groovy is a dynamic language, you can write
就其本身而言,这两个陈述之间没有太大区别;但由于 Groovy 是一种动态语言,您可以编写
def name = "Stephanie"
println name.toUpperCase() // no cast required
while you would need an explicit cast in the Java version
而您需要在 Java 版本中进行显式转换
Object name = "Stephanie";
System.out.println(((String) name).toUpperCase());
For that reason, def
makes much more sense in Groovy than unfounded use of Object
in Java.
出于这个原因,def
在 Groovy 中比Object
在 Java 中毫无根据地使用更有意义。
回答by Przemyslaw
You can experiment with groovy in the groovy web console http://groovyconsole.appspot.com/
您可以在 groovy 网络控制台http://groovyconsole.appspot.com/ 中试验 groovy
Your initial groovy date example works.
您最初的常规日期示例有效。