Java是否允许将getter作为方法参数传递?

时间:2019-01-16 16:26:43

标签: java methods parameter-passing

没有Lambda,谓词,接口。只是带有常规吸气剂的常规班。例如:

public int getWeight(){return weight;}

public int convertToLbs(int weight){some code here ...}


someObject.convertToLbs(someObject.getWeight())//valid???

谢谢

1 个答案:

答案 0 :(得分:2)

您当前的语法有效,但是您正在传递weight值,因为Java is pass-by-value

要为返回int的内容传递方法引用,可以使用IntSupplier

public int getWeight() { return weight; }
public int convertToLbs(IntSupplier s) { int w = s.getAsInt(); ... }

someObject.convertToLbs(someObject::getWeight);