Skip to content

Commit

Permalink
ServiceLoader + Plugin class loader
Browse files Browse the repository at this point in the history
  • Loading branch information
RustedBones committed Jan 13, 2025
1 parent 07acc19 commit 8f7b46f
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 91 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
com.github.sbt.avro.AvroCompilerBridge

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.github.sbt.avro

import java.net.{URL, URLClassLoader}

private object AvroCompilerPluginClassLoader {
private val JvmPrefixes = Array("java.", "jdk.")
private val CompilerInterface = classOf[AvroCompiler].getName
}

private class AvroCompilerPluginClassLoader(urls: Array[URL], parent: ClassLoader)
extends URLClassLoader(urls) {
import AvroCompilerPluginClassLoader.*

override def findClass(name: String): Class[?] = {
if (JvmPrefixes.exists(name.startsWith) || CompilerInterface == name) {
parent.loadClass(name)
} else {
super.findClass(name)
}
}
}
12 changes: 6 additions & 6 deletions plugin/src/main/scala/com/github/sbt/avro/SbtAvro.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import PluginCompat.*
import sbt.librarymanagement.DependencyFilter

import java.io.File
import java.util.ServiceLoader

/** Plugin for generating the Java sources for Avro schemas and protocols. */
object SbtAvro extends AutoPlugin {
Expand Down Expand Up @@ -244,19 +245,18 @@ object SbtAvro extends AutoPlugin {
// - output files are missing

// TODO Cache class loader
val avroClassLoader = new ChildFirstClassLoader(
val avroClassLoader = new AvroCompilerPluginClassLoader(
(AvroCompiler / dependencyClasspath).value
.map(toNioPath)
.map(_.toUri.toURL)
.toArray,
this.getClass.getClassLoader
)

val compiler = avroClassLoader
.loadClass(avroCompiler.value)
.getDeclaredConstructor()
.newInstance()
.asInstanceOf[AvroCompiler]
val compiler = ServiceLoader
.load(classOf[AvroCompiler], avroClassLoader)
.iterator()
.next()

compiler.setStringType(avroStringType.value)
compiler.setFieldVisibility(avroFieldVisibility.value.toUpperCase)
Expand Down

0 comments on commit 8f7b46f

Please sign in to comment.