如何将Groovy的课程理解为一流的公民 [英] How to understand Groovy's classes as first-class citizens

查看:87
本文介绍了如何将Groovy的课程理解为一流的公民的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名经验丰富的Java开发人员,但是一名新手Groovy程序员,目前我正在学习(迄今为止这非常棒)。作为参考,我正在阅读这份文件:

http://groovy.codehaus.org/Groovy+style+and+language+feature+guidelines+for+Java+developers



这很好,除了我不完全明白的一件事。文档中说类是一等公民,Groovy中不需要 .class 后缀。但是,如果是这种情况,我怎么才能在Groovy中引用对象的类型(即类)?



请考虑以下示例:

  def o = new Object()
println($ o,$ {o.class})
  

> java.lang.Object@da479dd,类java.lang.Object

预期输出感。但是当Groovy说他们说不需要 .class 后缀时,它指的是什么?

解决方案在Groovy和其他许多动态语言中,一切都是一个对象,包括类本身。



假设你在java中有一个Circle类。你需要调用Circle.getClass()来处理类对象。在许多动态语言中,类本身不需要指定。假设你有一堂课

  class Miu {} 

,并且以后每次引用Miu时都会引用类对象本身

  Miu.class 
Miu

都会评估为同一个对象



换句话说,C ++中的Java和早期版本没有eval(),所以类定义本身不能直接作为类对象。 OO模型更像是面向类的编程,而不是真正的面向对象,因为类是微妙的不是对象。在最近解释的动态语言中,类本身就是直接的对象。

I am an experienced Java developer, but a novice Groovy programmer, which I am learning at the moment (and it's great so far). As a reference I am reading this document:

http://groovy.codehaus.org/Groovy+style+and+language+feature+guidelines+for+Java+developers

That is all fine, except one thing I do not fully understand. The documentation says that classes are first-class citizens and the .class suffix is not needed in Groovy. But if that is the case how can I then refer to an object's type (i.e. class) in Groovy?

Consider the following example:

def o = new Object()
println("$o, ${o.class}")

Which gives me the following output:

java.lang.Object@da479dd, class java.lang.Object

This output is expected and makes sense. But what is the Groovy documentation than referring to when they say that the .class suffix is not needed?

解决方案

In Groovy and many other dynamic languages everything is an object, including class itself.

Say you have a class Circle in java. You need to call Circle.getClass() for an class object do deal with. In many dynamic languages, class itself does not need to be specified. Say you have a class

class Miu {}

and each later reference to Miu will be referencing to the class object itself

Miu.class
Miu

will both evaluate to the very same object

In other words, Java and earlier in C++ had no eval(), so class definition itself cannot be made into class object directly. OO model in them is more like class oriented programming rather than true object oriented, as classes are subtly not objects. In more recent interpreted dynamic languages classes themselves are directly objects.

这篇关于如何将Groovy的课程理解为一流的公民的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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