Это невозможно в Java. Однако это может быть достигнуто интерфейсом, хотя код становится сложным.
interface Block<T> {
void invoke(T arg);
}
class Utils {
public static <T> void forEach(Iterable<T> seq, Block<T> fct) {
for (T elm : seq)
fct.invoke(elm);
}
}
public class MyExample {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3);
Block<Integer> print = new Block<Integer>() {
private String foo() { // foo is declared inside main method and within the block
return "foo";
}
public void invoke(Integer arg) {
print(foo() + "-" + arg);
}
};
Utils.forEach(nums,print);
}
}