简体   繁体   中英

Does Java allow passing a getter as a method parameter?

No Lambda, Predicate, Interface. Just a regular class with a regular getter. For example:

public int getWeight(){return weight;}

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


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

Thanks

Your current syntax is valid but you are passing the weight value because Java is pass-by-value .

To pass a method reference for something that returns int you can use IntSupplier :

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

someObject.convertToLbs(someObject::getWeight);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM