2

How do I create Java 8 code that looks like this, without using the version with "com.sun.codemodel.JExpr.direct(String)":

Goal (the whole line would look like this, but the part I'm interested in is only the second parameter (java.util.function.Consumer) of the consumer method):

consume("someValue", myInstance::methodToBeUsed);

Currently in use to generate that part of the code:

JExpr.direct("instance" + "::" + "methodToBeUsed");

Just for clarity, the consume method:

import java.util.function.Consumer;

public class Foo {
    public static void consume(String value, Consumer<String> c) {
        c.accept(value);
    }
}
giro
  • 421
  • 1
  • 7
  • 19
  • 3
    Following the links in the tag wiki, I see a project, whose last update was in 2011, the year Java 7 was released and no Java 8 was in sight. Unless you can point to an alternative resource having a more recent version of `JCodeModel`, say 2014 or newer, I would not expect any active support for Java 8 features at all. Besides that, it looks like you expect the runtime instance generated for `myInstance::methodToBeUsed` to be converted back to a source code representation of `myInstance::methodToBeUsed`, which won’t work anyway. – Holger Apr 03 '17 at 17:00
  • Thanks for the Info, I haven't even thought of that. I'm not yet finished, so I haven't tried the generated code. But my generated code looks exactly like some other code I currently use, which works fine. So why wouldn't my Consumer code (myInstance::methodToBeUsed) work? – giro Apr 03 '17 at 17:07
  • 2
    Well, I’m not familiar with the library, but it looks like “`direct`” is supposed to pass the string directly to the underlying compiler, which will work if the compiler is newer than the library. (E.g. using [this API](https://docs.oracle.com/javase/8/docs/api/?javax/tools/package-summary.html) as backend). So if the library itself doesn’t understand the syntax, passing it via such a method like `direct` is the best support you can get. – Holger Apr 03 '17 at 17:11
  • Well thanks for the insights, without that info I would have probably tried and failed to find that info elsewhere. I'll finish this method asap and check if this will even work. If not I'll have to think about another way to reach my goal. Thanks a lot. – giro Apr 03 '17 at 17:18
  • 1
    for anyone interested: This project https://github.com/phax/jcodemodel will hopefully provide JCodeModel support for Java-8 with release 3.0 (only announced) – giro Apr 09 '17 at 15:27

0 Answers0