How to create a method to verify that an implementation satisfies an interface?

I have an interface (p) and an implementation (imp). If I do the following in code, then the check works:

if (!(imp instanceof p)) {
   logger.error(imp.getClass().getName()+ 
    " doesn't satisfy the interface "
   +p.getClass().getName());
   }

I tried turning it into a callable method as follows:

private boolean checkInterfaceImplementation(Object implemen, Object inter){
    return (implemen instanceof inter);
}

which failed.

Then I discovered that inter must be a specific type, and I cannot use a generic object. Then I found out about

"B.class.isAssignableFrom(A.getClass())"

Then I did:

System.out.println("B.class.isAssignableFrom(A
                    .getClass())");

There was a way out

True

I read more from this question. My question is: "Is this (the second implementation with" .isAssignableFrom ") the preferred or standard way to implement the specified method? Is there a way that this real implementation can cause problems?

+4
2

. , , , instanceof . , , .

, . "imp" "p", , "imp" "p". , , . , .

public interface Runs {
     public void run();
}

public class Cat implements Runs {
     int numLegs;
     public Cat() {
          this.numLegs = 4;
     }
     public void run() {
          System.out.println("does whatever running cats do");
     }
}

public class Human implements Runs {
     int numLegs;
     public Human() {
          this.numLegs = 2;
     }
     public void run() {
          System.out.println("does whatever running humans do");
     }
}
 public class Main {
         public static void main(String[] args) {
              Cat cat = new Cat();
              Human human = new Human();

              ArrayList<Runs> listOfRunners = new ArrayList<Runs>();
              listOfRunners.add(cat);
              listOfRunners.add(human);
              Runs runner = listOfRunners.get(0);
              /* no compiler error because by implementing Runs we guarantee it has run() method */
              runner.run();
              runner = listOfRunners.get(1);
              /* It doesn't matter what the object is. We don't care if it is cat or human */
              runner.run();
         }
    }
+2

, , - :

inter.getClass().isInstance(implemen)

, , , , .

+1

Source: https://habr.com/ru/post/1540760/


All Articles