我有以下 Java 类:
import org.apache.commons.lang3.builder.EqualsBuilder;
public class Animal {
private final String name;
private final int numLegs;
public Animal(String name, int numLegs) {
this.name = name;
this.numLegs = numLegs;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Animal animal = (Animal)o;
return new EqualsBuilder().append(numLegs, animal.numLegs)
.append(name, animal.name)
.isEquals();
}
}
以及以下 Spock 测试:
import spock.lang.Specification
class AnimalSpec extends Specification {
def 'animal with same name and numlegs should be equal'() {
when:
def animal1 = new Animal("Fluffy", 4)
def animal2 = new Animal("Fluffy", 4)
def animal3 = new Animal("Snoopy", 4)
def notAnAnimal = 'some other object'
then:
animal1 == animal1
animal1 == animal2
animal1 != animal3
animal1 != notAnAnimal
}
}
然后在运行覆盖时,第一个语句animal1 == animal1没有到达equals(o)方法:
Groovy/Spock 没有运行第一条语句有什么原因吗?我假设进行了微优化,但是当我犯错误时
@Override
public boolean equals(Object o) {
if (this == o) {
return false;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Animal animal = (Animal)o;
return new EqualsBuilder().append(numLegs, animal.numLegs)
.append(name, animal.name)
.isEquals();
}
测试仍然是绿色的。为什么会这样?
在周日早上编辑: 我做了一些更多的测试,发现它甚至不是优化,但在运行此测试时甚至会导致大量调用的开销:
class AnimalSpec extends Specification {
def 'performance test of == vs equals'() {
given:
def animal = new Animal("Fluffy", 4)
when:
def doubleEqualsSignBenchmark = 'benchmark 1M invocation of == on'(animal)
def equalsMethodBenchmark = 'benchmark 1M invocation of .equals(o) on'(animal)
println "1M invocation of == took ${doubleEqualsSignBenchmark} ms and 1M invocations of .equals(o) took ${equalsMethodBenchmark}ms"
then:
doubleEqualsSignBenchmark < equalsMethodBenchmark
}
long 'benchmark 1M invocation of == on'(Animal animal) {
return benchmark {
def i = {
animal == animal
}
1.upto(1_000_000, i)
}
}
long 'benchmark 1M invocation of .equals(o) on'(Animal animal) {
return benchmark {
def i = {
animal.equals(animal)
}
1.upto(1_000_000, i)
}
}
def benchmark = { closure ->
def start = System.currentTimeMillis()
closure.call()
def now = System.currentTimeMillis()
now - start
}
}
我预计这个测试会成功,但我运行了几次,它从来没有绿色......
1M invocation of == took 164 ms and 1M invocations of .equals(o) took 139ms
Condition not satisfied:
doubleEqualsSignBenchmark < equalsMethodBenchmark
| | |
164 | 139
false
当调用次数增加到 1B 时,优化变得可见:
1B invocation of == took 50893 ms and 1B invocations of .equals(o) took 75568ms
最佳答案
这个优化存在是因为下面的表达式:
animal1 == animal1
Groovy 转换为以下方法调用:
ScriptBytecodeAdapter.compareEqual(animal1, animal1)
现在,如果我们看一下 this method's source code我们会发现,在第一步中,这个方法使用了很好的旧 Java 对象引用比较——如果表达式的两边都指向同一个引用,它只返回 true。和 equals(o)或 compareTo(o) (在比较实现 Comparable<T> 接口(interface)的对象的情况下)方法不会被调用:
public static boolean compareEqual(Object left, Object right) {
if (left==right) return true;
Class<?> leftClass = left==null?null:left.getClass();
Class<?> rightClass = right==null?null:right.getClass();
// ....
}
在你的情况下,left和 right变量指向相同的对象引用,因此方法中的第一个检查匹配和 true被退回。
如果您在此位置放置一个断点(ScriptBytecodeAdapter.java 第 685 行),您将看到调试器到达该点并返回 true从该方法的第一行开始。
作为一个很好的练习,您可以看一下下面的示例。这是一个使用 Animal_script.groovy 的简单 Groovy 脚本(称为 Animal.java )类并进行对象比较:
def animal1 = new Animal("Fluffy", 4)
def animal2 = new Animal("Fluffy", 4)
def animal3 = new Animal("Snoopy", 4)
println animal1 == animal1
如果编译并打开Animal_script.class IntelliJ IDEA 中的文件(因此它可以反编译回 Java),您将看到如下内容:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import groovy.lang.Binding;
import groovy.lang.Script;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class Animal_script extends Script {
public Animal_script() {
CallSite[] var1 = $getCallSiteArray();
}
public Animal_script(Binding context) {
CallSite[] var2 = $getCallSiteArray();
super(context);
}
public static void main(String... args) {
CallSite[] var1 = $getCallSiteArray();
var1[0].call(InvokerHelper.class, Animal_script.class, args);
}
public Object run() {
CallSite[] var1 = $getCallSiteArray();
Object animal1 = var1[1].callConstructor(Animal.class, "Fluffy", 4);
Object animal2 = var1[2].callConstructor(Animal.class, "Fluffy", 4);
Object animal3 = var1[3].callConstructor(Animal.class, "Snoopy", 4);
return var1[4].callCurrent(this, ScriptBytecodeAdapter.compareEqual(animal1, animal1));
}
}
如您所见,animal1 == animal1被 Java 运行时视为 ScriptBytecodeAdapter.compareEqual(animal1, animal1)) .
希望对您有所帮助。
关于java - Groovy == 运算符未达到 Java equals(o) 方法 - 这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52555849/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2