2

This is a question that has been bothering me for a while.

In frameworks like Jersey we have interface(s) that we can subclass to add some functionality to our program. for example to add request filtering in a RESt application we can implement ContainerRequestFilter then Voila we got authentication.

My question is how does the framework/library know that we have subclass one of its interfaces?

as per my understanding you can't instantiate an interface, only its subclass such as:

public interface Greeter{
    void sayHi();
}

public class SpanishGreeter implements Greeter{
    @override
    void sayHi(){
        System.out.println("Hola");
    }
}

public class Controller{
   public void main(String[] args){
       //We must know the name of subclass to instantiate?
       Greeter spanishG = new SpanishGreeter();
   }
}
Claudiga
  • 427
  • 1
  • 4
  • 15

3 Answers3

3

What you're looking for is classpath scanning.

This isn't a trivial task, and it's pretty much what the name says: you basically need to scan the classpath and load every class you find (although the typical implementation will allow you to limit your search to certain packages and its subpackages only, to stop from things going really crazy).

There are no special tricks in the Java language that would make this task easy.

The good news is that you don't need to write it from scratch, as frameworks like Spring already have it built in, or if you want to have complete low-level control, you can use a dedicated library like Reflections.

biziclop
  • 48,926
  • 12
  • 77
  • 104
0

I think instanceof keyword helps in it.

System.out.println(spanishG instanceof Greeter);  // true
gprathour
  • 14,813
  • 5
  • 66
  • 90
  • but in order for that to work spanishG must have already been instantiated somehow? in a context where we have no idea what the name of the subclass would be or if there was even one provided – Claudiga Nov 13 '17 at 10:29
0

That happens due to Polymorphism. The code you mentioned

Greeter spanishG = new SpanishGreeter();

That has reference of parent(in you case interface). On run time it checks weather there is a child class implementing the method if yes then it calls child class behaviour. And in your class you are instantiating with child class on run time JVM knows you have provided implementation.

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
  • I know about Polymorphism, but how is that instance made when we have no idea about what the name of the implementation class is or if an implementation is even provided – Claudiga Nov 13 '17 at 10:26
  • This is what polymorphism all about. It checks at run time. – Abdul Waheed Nov 13 '17 at 10:28