Skip to content

Instantly share code, notes, and snippets.

@jmini
Created March 25, 2021 08:13
Show Gist options
  • Select an option

  • Save jmini/f02e7c044700179251dc24b8fd1e5275 to your computer and use it in GitHub Desktop.

Select an option

Save jmini/f02e7c044700179251dc24b8fd1e5275 to your computer and use it in GitHub Desktop.
Spoon test with compile errors
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS fr.inria.gforge.spoon:spoon-core:8.4.0
//DEPS org.slf4j:slf4j-simple:1.7.30
import java.util.List;
import java.util.Set;
import spoon.Launcher;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtField;
import spoon.reflect.declaration.CtMethod;
public class SpoonMain {
public static void main(String... args) {
String content = ""
+ "package lorem;\n"
+ "\n"
+ "public class Ipsum {\n"
+ "\n"
+ " private String name\n" // compile error ';' is missing
+ "\n"
+ " public String getName() {\n"
+ " \n" // compile error: no return statement
+ " }\n"
+ "\n"
+ " public void setName(String name) {\n"
+ " this.name = name;\n"
+ " \n" // compile error '}' is missing
+ "}";
System.out.println("=== code start === ");
System.out.println(content);
System.out.println("=== code end === ");
CtClass<?> cls = Launcher.parseClass(content);
Set<CtMethod<?>> allMethods = cls.getMethods();
for (CtMethod<?> ctMethod : allMethods) {
System.out.println("-- method -- ");
System.out.println("name: " + ctMethod.getSimpleName());
System.out.println("parameters: " + ctMethod.getParameters());
System.out.println("type: " + ctMethod.getType());
}
List<CtField<?>> typeFields = cls.getFields();
for (CtField<?> f : typeFields) {
System.out.println("-- type -- ");
System.out.println("name: " + f.getSimpleName());
System.out.println("type: " + f.getType());
}
}
}
@jmini

jmini commented Mar 25, 2021

Copy link
Copy Markdown
Author

Small experiment with Spoon.

jbang can be used to run the code inside the SpoonMain class.
Here is the output I get:

$ jbang SpoonMain.java
[jbang] Resolving dependencies...
[jbang]     Resolving fr.inria.gforge.spoon:spoon-core:8.4.0...Done
[jbang]     Resolving org.slf4j:slf4j-simple:1.7.30...Done
[jbang] Dependencies resolved
[jbang] Building jar...
=== code start === 
package lorem;

public class Ipsum {

    private String name

    public String getName() {
        
    }

    public void setName(String name) {
        this.name = name;
    
}
=== code end === 
-- method -- 
name: getName
parameters: []
type: String
-- method -- 
name: setName
parameters: [String name]
type: void
-- type -- 
name: name
type: String

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment