0

I have a class with a long name, and a static method used like this:

class VeryLongDescriptiveName {

   private someMethod() {
      Map<String, HashSet<String>> map = ...

      HashSet<String> newValue = ...

      map.merge("newKey", newValue, VeryLongDescriptiveName::allAllNewToOld);
   }

   private static <T> HashSet<T> addAllNewToOld(HashSet<T> oldSet, HashSet<T> newSet) {
      oldSet.addAll(newSet);
      return oldSet;
   }
}

I don't like having to repeat the full class name when passing the reference VeryLongDescriptiveName::addAllNewToOld. I can make the method non-static and do this::addAllNewToOld and I can move the method out into a separate utility class Util::addAllNewToOld.

It seems strange that Java allows calling a local static method without the class name, or doing the same with static import but does not support passing local static method by reference.

Is there a way to achieve this in Java?

alexandroid
  • 1,469
  • 2
  • 15
  • 32
  • I'm not sure exactly what you're trying to achieve, but you can definitely just type the method name in `someMethod`'s body. There is no need to put `this::` and remove static, and no need to write the class name in front of it. You just write `addAllNewToOld();` – Mazzone Nov 19 '19 at 14:55
  • @Mazzone Yes, that works, but in my case I need to pass a reference of a method for a functor argument of another method ("Map.merge()" in this example). – alexandroid Nov 19 '19 at 16:27

0 Answers0