0

I am trying to write a Utility library (jar),

Inside Library

interface ConfigBuilder
{
  public Configuration buildConfiguration()
}

class SomeLogic
{
  private void someMethod()
  {
    ConfigBuilder  builder = // GET IMPLEMETATION OBJECT FROM IMPLEMENTOR OF LIBRARY ??
    Configuration c = builder.buildConfiguration();
    method2(c)
    //Some logic
  }
}

How can I do this ?? I am using Gradle as build tool. As being library We don't have an implementation class. Max we can do is - Who ever is implementing this library create a class with name com.xyz.lib.implimentation.ConfigBuilderImpl

implementing ConfigBuilder Interface

What I tried I was

this.getClass.getClassLoader.loadClass("com.xyz.lib.implimentation.ConfigBuilderImpl")

Then I am getting Exception

java.lang.ClassNotFoundException: com.xyz.lib.implimentation.ConfigBuilderImpl
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Nirbhay Mishra
  • 1,629
  • 3
  • 19
  • 35
  • 3
    That looks like **Java** code, why did you tag it with **Scala**? - Anyways, the best idea is to leet your caller to pass you the implementation explicitly instead of relying in black magic. – Luis Miguel Mejía Suárez Jul 13 '20 at 17:53
  • I have been a java developer for some time, learning scala, Both are JVM based the concept seems the same in both. – Nirbhay Mishra Jul 14 '20 at 04:56
  • So why not tagging **Kotlin**, **Groovy**, **Jython**, **Cloujure**, etc? You didn't mentioned anything related to **Scala** in the question. Also, which concept? Runtime reflection based dependency injection? Sorry, but no; that may be very common in **Java** but it is usually avoided in **Scala**. – Luis Miguel Mejía Suárez Jul 14 '20 at 12:38

1 Answers1

0

You can use SPI, the Service Provider Interface.

https://docs.oracle.com/javase/tutorial/ext/basics/spi.html

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25