1

我使用 eclipse ide 从以下代码片段中得到了意想不到的结果:

class Example(String s = "init") {
    shared String a() => "Func 1";
    shared String b = "Attr 1";
    shared String c(Integer i) { return "Func 2"; }
}


shared
void run() {    

  // 1.
  print("getAttributes: " + `Example`.getAttributes().string);
  print("getMethods:    " + `Example`.getMethods().string);
  // prints:   []  
  // i.e. doesnt print any attribute or method

  // 2.
  value e = Example()
  type(e);  // error
  e.type(); // error, should be replaced by the ide with the above version.

}

广告 1.) 结果我得到:

getAttributes: []
getMethods:    []

我期望包含属性或方法的列表。

广告 2.) 医生说:

“type() 函数将返回给定实例的封闭类型,它只能是 ClassModel,因为只能实例化类。......”

但是我找不到 type() 函数和其他与元编程相关的函数,即我没有得到工具提示,而是得到一个运行时(!)错误:

Exception in thread "main" com.redhat.ceylon.compiler.java.language.UnresolvedCompilationError: method or attribute does not exist: 'type' in type 'Example'

那么,作为函数的反引号 `Example`.... 的等价物在哪里?

4

1 回答 1

1
  1. `Example`.getAttributes()返回一个空列表,因为getAttributes它接受三个类型参数:Container, Get, Set. 当调用 asgetAttributes()时,类型检查器尝试推断它们,但由于没有信息(没有具有适当类型的参数),推断的类型参数是Nothing. 由于Nothing不是任何类成员的容器,因此结果列表为空。改为使用getAttributes<>()默认类型参数,或显式指定它们(例如getAttributes<Example>())。与getMethods(). 在线尝试

  2. type函数在里面ceylon.language.meta,需要导入:import ceylon.language.meta { type }. 一旦你这样做(并删除该e.type()行),编译错误就会消失。

  3. 如果你直接想要一个函数的元对象,你可以写`Example.a`.

于 2016-07-08T10:45:42.790 回答