-1
public interface Animal {
    public static void makeNoise() {

    }
}

public class Sheep implements Animal {
    public static void makeNoise() {

    }
}

Clients should be able to just do the following and they should not know what object is getting injected from behind the scenes?

Animal.makeNoise();

Factory pattern still needs to know the key that maps to a concrete class so I am looking for other options. is there a way I can overwrite the ClassLoader for Animal and somehow inject the sheep object without using any frameworks like spring or whatever? any code sample for this kind of small example would be great!

user1870400
  • 6,028
  • 13
  • 54
  • 115
  • Is this not what method/constructor DI aims to do? – Tdorno May 17 '16 at 01:59
  • The closest thing built into the JDK itself is the "Service provider" JAR manifest. That's what JDBC drivers use to register themselves. This questions seems similar: http://stackoverflow.com/q/1144916/14955 – Thilo May 17 '16 at 02:08
  • Animal is an interface from where you have a static method. Isn't that tied with the interface itself? All your `makeNoise` methods are static. – randominstanceOfLivingThing May 17 '16 at 02:10
  • 1
    Why do you need that? I believe it is an [X-Y question](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) Maybe you want to do something like SLF4J? Logging impl need to provide a `StaticLoggerBinder` – Adrian Shum May 17 '16 at 02:45

1 Answers1

0

You may use factory pattern. Here's the reference: http://www.oodesign.com/factory-pattern.html. or this reference: http://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Good luck.

salirajr
  • 54
  • 1
  • Factory Method would not solve the problem here because clients still have to know some key that maps to the concrete class. – user1870400 May 17 '16 at 01:55
  • Why? The client does not need to know a "key" as long as the factory does. And the factory can be configured by some classpath-scanning logic. – Thilo May 17 '16 at 02:06
  • You may encapsulate it. It will base on how you utilized the pattern. – salirajr May 17 '16 at 02:09