INRIA / INRIA/spoon

[Bug]: NPE in `Refactoring.copyMethod` when method has no parent type

Open
#5,459 0 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
2k
Forks
392
Avg merge
11h 24m
Merged PRs (30d)
36

Description

### Describe the bug

Using `Refactoring.copyMethod` to copy methods causes a `NullPointerException` when the method has no parent type.

### Source code you are trying to analyze/transform

```Java
public class Test {
void foo() {
}
}
```

### Source code for your Spoon processing

```Java
Launcher spoon = new Launcher();

spoon.addInputResource(new VirtualFile(
"""
public class Test {
void foo() {
}
}
"""));
CtModel model = spoon.buildModel();
CtMethod method = model.getElements(new TypeFilter<>(CtMethod.class)).get(0);

System.out.println("Original:");
System.out.println(method);
System.out.println();

System.out.println("Removed from parent:");
method.delete();
method.setParent(null);
System.out.println(method);
System.out.println();

System.out.println("Copied:");
CtMethod copy = Refactoring.copyMethod(method);
System.out.println(copy);
```

### Actual output

```Java
Original:
void foo() {
}

Removed from parent:
void foo() {
}

Copied:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "spoon.reflect.declaration.CtType.getMethodsByName(String)" because "parent" is null
at spoon.refactoring.Refactoring.copyMethod(Refactoring.java:92)
at SpoonTest_copyMethod_noParent.main(SpoonTest_copyMethod_noParent.java:36)
```

### Expected output

```Java
Original:
void foo() {
}

Removed from parent:
void foo() {
}

Copied:
void fooCopy() {
}
```

### Spoon Version

10.4.1

### JVM Version

openjdk version "17" 2021-09-14 OpenJDK Runtime Environment (build 17+35-2724) OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing)

### What operating system are you using?

Windows 10 64 bit

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.