Skip to content

Instantly share code, notes, and snippets.

@eungju
Last active June 13, 2021 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eungju/ec10f034f239e03d261e256d75179363 to your computer and use it in GitHub Desktop.
Save eungju/ec10f034f239e03d261e256d75179363 to your computer and use it in GitHub Desktop.
jaeger-zipkin이 객체의 private 필드에 접근하지 않게 한다.
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import io.jaegertracing.zipkin.internal.V2SpanConverter
import java.lang.reflect.Field
import java.lang.reflect.Modifier
import java.lang.invoke.MethodHandles
import java.lang.invoke.VarHandle
class FixZipkinV2Reporter(gson: Gson = PRIVACY_RESPECTING_GSON) {
init {
//make it accessible
val field = V2SpanConverter::class.java.getDeclaredField("gson")
field.isAccessible = true
//make it modifiable
try {
val modifiersField = Field::class.java.getDeclaredField("modifiers")
modifiersField.isAccessible = true
modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv())
} catch (e: NoSuchFieldException) {
//Java 12 does not allow access to the fields of java.lang.reflect.Field.
val accessModifiers: VarHandle = MethodHandles.privateLookupIn(Field::class.java, MethodHandles.lookup())
.findVarHandle(Field::class.java, "modifiers", Int::class.java)
accessModifiers.set(field, field.modifiers and Modifier.FINAL.inv())
}
//modify
field.set(null, gson)
}
companion object {
@JvmField
val PRIVACY_RESPECTING_GSON: Gson = GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT or Modifier.STATIC or Modifier.PRIVATE)
.create()
}
}
import io.jaegertracing.zipkin.internal.V2SpanConverter
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Test
class FixZipkinV2ReporterTest {
private val gson = FixZipkinV2Reporter.PRIVACY_RESPECTING_GSON
class WithPrivateField(
@JvmField
val name: String,
@JvmField
private val phoneNumber: String
)
@Test
fun excludePrivateFields() {
val encoded = gson.toJson(WithPrivateField("john", "282"))
assertEquals("{\"name\":\"john\"}", encoded)
}
@Test
fun patch() {
FixZipkinV2Reporter(gson)
val field = V2SpanConverter::class.java.getDeclaredField("gson")
field.isAccessible = true
assertSame(gson, field.get(null))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment