Groovy def和Java对象之间的区别? [英] Difference between Groovy def and Java Object?
问题描述
Groovy:
def name =stephanie
Java:
对象名称=stephanie
因为两者似乎都充当了与它们交互的对象,因此我必须将它们转换为其原始的预期类型。
我最初是在寻找一个java等价物C#的动态类( Java相当于C#动态类类型?)和有人建议看看Groovy的 def
例如我对groovy的def的印象是我可以做以下:
def DOB = new Date(1998,5,23);
int x = DOB.getYear();
但是这不会建立
steph
解决方案编辑:
我发现错误是因为我有一个使用def定义的公共属性的Groovy类(在我的示例中为DOB)然后试图从.java类访问它们(在我上面的示例中调用.getYear())。它是一个新手的错误,但问题是一旦对象离开了Groovy文件,它就被当作对象。感谢您的帮助!
本身,这两种说法没有太大的区别。但由于Groovy是一种动态语言,因此您可以编写
def name =Stephanie
println name.toUpperCase )//不需要强制转换
您需要在Java版本中进行明确的转换
对象名称=Stephanie;
System.out.println(((String)name).toUpperCase());
因此, def
使得更多在Groovy中感觉比在Java中使用 Object
没有根据。
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
for example my impression of groovy's def is that I could do the following:
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!
Per se, there is not much difference between those two statements; but since Groovy is a dynamic language, you can write
def name = "Stephanie"
println name.toUpperCase() // no cast required
while you would need an explicit cast in the Java version
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.
这篇关于Groovy def和Java对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!