我有一个枚举类型类:
public enum Operation {
PLUS() {
@Override
double apply(double x, double y) {
// ERROR: Cannot make a static reference
// to the non-static method printMe()...
printMe(x);
return x + y;
}
};
private void printMe(double val) {
System.out.println("val = " + val);
}
abstract double apply(double x, double y);
}
正如你在上面看到的,我定义了一个 enum 类型,它的值是 PLUS。它包含一个特定于常量的主体。在它的正文中,我尝试调用 printMe(val);,但我得到了编译错误:
Cannot make a static reference to the non-static method printMe().
为什么会出现此错误?我的意思是我正在重写 PLUS 正文中的抽象方法。为什么它在 static 范围内?如何摆脱它?
我知道在 printMe(){...} 上添加 static 关键字可以解决问题,但我很想知道是否有其他方法保持 printMe() 非静态?
另一个问题,与上述问题非常相似,但这次错误消息听起来相反,即 PLUS(){...} 具有非静态上下文:
public enum Operation {
PLUS() {
// ERROR: the field "name" can not be declared static
// in a non-static inner type.
protected static String name = "someone";
@Override
double apply(double x, double y) {
return x + y;
}
};
abstract double apply(double x, double y);
}
我尝试声明一个 PLUS 特定的 static 变量,但最终出现错误:
the field "name" can not be declared static in a non-static inner type.
如果 PLUS 是匿名类,为什么我不能在 PLUS 中定义静态常量?这两条错误消息听起来相互矛盾,因为第一条错误消息说 PLUS(){...} 有 static 上下文,而第二条错误消息说 PLUS(){...} 具有非静态上下文。我现在更困惑了。
最佳答案
这是一个奇怪的案例。
看来问题是:
在这种情况下,私有(private)成员应该是可访问的(6.6.1。):
Otherwise, the member or constructor is declared
private, and access is permitted if and only if it occurs within the body of the top level class that encloses the declaration of the member or constructor.
但是,私有(private)成员不会被继承 (8.2):
Members of a class that are declared
privateare not inherited by subclasses of that class.
因此,printMe不是匿名子类的成员,编译器会在父类(super class)中搜索它* Operation (15.12.1):
If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.
This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking for methods in an enclosing class and its superclass hierarchy.
这就是奇怪的地方。因为printMe在一个也包含的类中找到PLUS ,调用该方法的对象被确定为 Operation 的封闭实例, 不存在 (15.12.4.1):
Otherwise, let T be the enclosing type declaration of which the method is a member, and let n be an integer such that T is the n'th lexically enclosing type declaration of the class whose declaration immediately contains the method invocation. The target reference is the n'th lexically enclosing instance of
this.It is a compile-time error if the n'th lexically enclosing instance of
thisdoes not exist.
简而言之,因为 printMe只是 Operation 的成员(而不是继承),编译器被迫调用 printMe 在一个不存在的外部实例上。
但是,该方法仍然可以访问,我们可以通过限定调用来找到它:
@Override
double apply(double x, double y) {
// now the superclass is searched
// but the target reference is definitely 'this'
// vvvvvv
super.printMe(x);
return x + y;
}
The two error messages sound contradictory to each other [...].
是的,这是该语言的一个令人困惑的方面。一方面,匿名类永远不是静态的(15.9.5),另一方面,匿名类表达式可以出现在静态上下文中,因此没有封闭实例(8.1.3) .
An anonymous class is always an inner class; it is never
static.
An instance of an inner class
Iwhose declaration occurs in a static context has no lexically enclosing instances.
为帮助理解其工作原理,以下是一个格式化示例:
class Example {
public static void main(String... args) {
new Object() {
int i;
void m() {}
};
}
}
<i>italics</i> 中的所有内容是静态上下文。从<b>bold</b> 中的表达式派生的匿名类被认为是内部的和非静态的(但没有 Example 的封闭实例)。
由于匿名类是非静态的,它不能声明静态非常量成员,尽管它本身是在静态上下文中声明的。
* 除了使事情变得模糊之外,Operation 的事实是一个枚举完全不相关(8.9.1):
The optional class body of an enum constant implicitly defines an anonymous class declaration that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes [...].
关于java - 特定于枚举常量的类主体是静态的还是非静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28964926/
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c
我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案
假设我有一个FireNinja我的数据库中的对象,使用单表继承存储。后来才知道他真的是WaterNinja.将他更改为不同的子类的最干净的方法是什么?更好的是,我很想创建一个新的WaterNinja对象并替换旧的FireNinja在数据库中,保留ID。编辑我知道如何创建新的WaterNinja来self现有FireNinja的对象,我也知道我可以删除旧的并保存新的。我想做的是改变现有项目的类别。我是通过创建一个新对象并执行一些ActiveRecord魔法来替换行,还是通过对对象本身做一些疯狂的事情,或者甚至通过删除它并使用相同的ID重新插入来做到这一点,这是问题的一部分。
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我