Skip to content

Commit 5beb0de

Browse files
committed
fix: set Thread Context ClassLoader correctly when invoking handler constructor
1 parent 7df8be8 commit 5beb0de

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

invoker/core/src/main/java/com/google/cloud/functions/invoker/HttpFunctionExecutor.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,16 @@ public static HttpFunctionExecutor forClass(Class<?> functionClass) {
4848
+ HttpFunction.class.getName());
4949
}
5050
Class<? extends HttpFunction> httpFunctionClass = functionClass.asSubclass(HttpFunction.class);
51+
ClassLoader oldContextLoader = Thread.currentThread().getContextClassLoader();
5152
try {
53+
Thread.currentThread().setContextClassLoader(httpFunctionClass.getClassLoader());
5254
HttpFunction httpFunction = httpFunctionClass.getConstructor().newInstance();
5355
return new HttpFunctionExecutor(httpFunction);
5456
} catch (ReflectiveOperationException e) {
5557
throw new RuntimeException(
5658
"Could not construct an instance of " + functionClass.getName() + ": " + e, e);
59+
} finally {
60+
Thread.currentThread().setContextClassLoader(oldContextLoader);
5761
}
5862
}
5963

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.google.cloud.functions.invoker;
2+
3+
import static com.google.common.truth.Truth.assertThat;
4+
import static com.google.common.truth.Truth8.assertThat;
5+
6+
import com.google.cloud.functions.HttpFunction;
7+
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.junit.runners.JUnit4;
11+
import java.lang.ClassLoader;
12+
import com.google.cloud.functions.HttpResponse;
13+
import com.google.cloud.functions.HttpRequest;
14+
15+
@RunWith(JUnit4.class)
16+
public class HttpFunctionExecutorTest {
17+
private static ClassLoader customClassLoader = new ClassLoader(ClassLoader.getSystemClassLoader()) {
18+
19+
};
20+
21+
public static class HelloWorld implements HttpFunction {
22+
public HelloWorld() {
23+
assertThat(Thread.currentThread().getContextClassLoader() != customClassLoader);
24+
}
25+
26+
@Override
27+
public void service(HttpRequest request, HttpResponse response) throws Exception {
28+
assertThat(Thread.currentThread().getContextClassLoader() != customClassLoader);
29+
}
30+
}
31+
32+
@Test
33+
public void canDetermineTypeArgument() {
34+
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
35+
Thread.currentThread().setContextClassLoader(customClassLoader);
36+
HttpFunctionExecutor.forClass(HelloWorld.class);
37+
Thread.currentThread().setContextClassLoader(oldClassLoader);
38+
}
39+
}

0 commit comments

Comments
 (0)