java - Creating String representation of lambda expression -


this question has answer here:

for debugging purposes trying create string representations of lambda expressions (specifically of predicates, though interesting other lambda expressions too) in java 8. idea this:

public class whatever {      private static <t> string predicatetostring(predicate<t> predicate) {         string representation = ... // magic         return representation;     }      public static void main(string[] args) {         system.out.println(whatever.<integer>predicatetostring(i -> % 2 == 0));     }  } 

and output i -> % 2 == 0 (or logically equivalent). tostring() method seems of no help, output com.something.whatever$$lambda$1/1919892312@5e91993f (which guess expected tostring() not overridden).

i'm not sure whether possible, e.g. reflection, haven't been able find on far. ideas?

the simplest thing come creating "named predicate" gives predicates name or description, useful tostring:

public class namedpredicate<t> implements predicate<t> {     private final string name;     private final predicate<t> predicate;      public namedpredicate(string name, predicate<t> predicate) {         this.name = name;         this.predicate = predicate;     }      @override     public boolean test(t t) {         return predicate.test(t);     }      @override     public string tostring() {         return name;     }      public static void main(string... args) {         predicate<integer> iseven = new namedpredicate<>("iseven", -> % 2 == 0);         system.out.println(iseven); // prints iseven     } } 

arguably giving predicates names or descriptions makes code use them bit easier understand also:

stream.of(1, 2, 3, 4)         .filter(iseven)         .foreach(system.out::println); 

a stranger idea might derive "structural" description of predicate, i.e. output given inputs? work best when input set finite , small (e.g. enums, booleans or other restricted set), guess try small set of "random" integers integer predicates well:

private static map<boolean, list<integer>> testpredicate(predicate<integer> predicate) {     return stream.of(-35, -3, 2, 5, 17, 29, 30, 460)             .collect(collectors.partitioningby(predicate)); } 

for iseven, return {false=[-35, -3, 5, 17, 29], true=[2, 30, 460]}, don't think clearer if manually give them description, perhaps useful predicates not under control.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -