Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot close over local variables #916

Closed
atorstling opened this issue Oct 13, 2015 · 3 comments
Closed

Cannot close over local variables #916

atorstling opened this issue Oct 13, 2015 · 3 comments

Comments

@atorstling
Copy link
Contributor

Java8StepDefinition and more specifically ConstantPoolTypeIntrospector confuses closed variables with arguments to the accept function. This has the consequence that you are unable to close over local variables.

For example, if you define something like

class Steps implements En {
  Steps() {
      String prefix = "hello ";
      When("^blabla$", () -> prefix + "world" ); 
  }
}

, the lambda closes over the prefix variable. Subsequently, the ConstantPoolTypeIntrospector will read out a typeString not of the expected ()V, but of (Ljava/lang/String;)V. Java8StepDefinition will therefore get typeArguments of Type[]{ String.class }. It will then proceed looking for a method called accept with a single Object argument, which will fail (it treats all arguments as Object arguments, disregarding the specific type). In other words, it "thinks" that the lamda looks as follows:

class Steps implements En {
  Steps() {
      String prefix = "hello ";
      When("^blabla$", (prefix) -> prefix + "world" ); 
  }
}

, even though prefix is implicitly passed. I believe this could be solved by simply calling clazz.getDeclaredMethod("accept"), instead of looking in the constant pool, which evidently exposes implicit dependencies as well as explicit ones.

This problem is not present if you close over fields in the Steps class.

The exception you get when this happens is:

cucumber.runtime.CucumberException: java.lang.NoSuchMethodException:  com.example.Steps$$Lambda$3/358849801.accept(java.lang.Object)
    at cucumber.runtime.java.JavaBackend.addStepDefinition(JavaBackend.java:164)
    at cucumber.api.java8.En.When(En.java:370)
    at com.example.Steps.<init>(Steps.java:54)

I'm using cucumber 1.2.4

@aslakhellesoy
Copy link
Contributor

Interesting. Would you be able to send a pull request with your proposed fix?

@atorstling
Copy link
Contributor Author

Sure thing, please see above.

@lock
Copy link

lock bot commented Oct 25, 2018

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators Oct 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants