简体   繁体   English

Groovy def和Java对象之间的区别?

[英]Difference between Groovy def and Java Object?

I'm trying to figure out the difference between 我想弄清楚它们之间的区别

Groovy: Groovy的:

def name = "stephanie"

Java: 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相当于C#动态类类型的Java? ),并建议查看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). 解决方案编辑:弄清楚错误,因为我有一个groovy类与公共属性(在我的DOB上面的例子)用def定义,但后来正试图从.java类访问它们(在我上面的例子中调用.getYear( ) 在上面)。 Its a rookie mistake but the problem is once the object leaves a Groovy file it is simply treated as a Object. 它是一个菜鸟错误,但问题是一旦对象离开Groovy文件,它就被视为一个Object。 Thanks for all your help! 感谢你的帮助!

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中比在Java中毫无根据地使用Object更有意义。

You can experiment with groovy in the groovy web console http://groovyconsole.appspot.com/ 您可以在groovy Web控制台中试验groovy http://groovyconsole.appspot.com/

Your initial groovy date example works. 您的初始groovy日期示例有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM