如何用一个主函数定义一个groovy类来创建一个新对象,该对象是另一个类的一个实例 [英] how to define a groovy class with a main function that creates a new object that is an instance of another class

查看:1006
本文介绍了如何用一个主函数定义一个groovy类来创建一个新对象,该对象是另一个类的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我是一个时髦的新手,显然只是没有得到它,但
请任何人都可以解释为什么我在编译
以下代码时遇到这些错误:



tc.groovy:

  class t 
{
int v;
t(){v = 1; }
}
class tt
{
static void main(String [] args)
{
t v = new t();


$ / code $ / pre
$ b $ groovyc tc.groovy

org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败:

tc.groovy:11:找到明显变量'v'在静态作用域中,但不涉及局部变量,静态字段或类。可能的原因:

您试图从静态上下文中引用绑定中的变量或实例变量。



拼写错误的类名或静态导入的字段。请检查拼写。



您试图使用方法'v',但在文法不允许的地方省略括号。

  @ line 11,column 12. 
tv = new t();



<1>错误

我所要做的就是编译一个声明2个类的groovy程序,一个带有main()方法,它需要实例化另一个类的实例。有什么办法可以在groovy中做到这一点?

解决方案

将您的类名大写为T,更改构造函数以匹配,将工作。 Groovy要求类型名称以大写字母开头。



这与Java有所不同。在Java中,没有硬性规定类名必须大写,这只是一个惯例。在Groovy中,它不仅仅是一个约定,语言的语法假定所有类都以大写字母开始。


Sorry, I'm a groovy newbie and obviously just not getting it, but please could anyone explain why I get these errors when compiling the following code:

tc.groovy:

 class t
 {
   int v;
   t() { v = 1; }
 }
 class tt
 {
   static void main(String[] args)
   {
     t v = new t();
   }
 }

$ groovyc tc.groovy

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:

tc.groovy: 11: Apparent variable 'v' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:

You attempted to reference a variable in the binding or an instance variable from a static context.

You misspelled a classname or statically imported field. Please check the spelling.

You attempted to use a method 'v' but left out brackets in a place not allowed by the grammar.

 @ line 11, column 12.
        t v = new t();
          ^

1 error

All I'm trying to do is compile a groovy program that declares 2 classes, one with a main() method, which needs to instantiate an instance of the other class. Is there any way to do this in groovy?

解决方案

Capitalize your class name to T, change the constructor to match, and it will work. Groovy requires that the type name begin with a capital letter.

This is a difference from Java. In Java there is no hard requirement that class names must be capitalized, it is only a convention. In Groovy it is not just a convention, the grammar of the language assumes all classes will start with a capital letter.

这篇关于如何用一个主函数定义一个groovy类来创建一个新对象,该对象是另一个类的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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