Java. Permit the interface only to the heirs of a certain class



  • I'll try and explain why.

    By the core of the system, I'm gonna mean some code that I can't get right.

    There's an abstract class. PersistObject

    The system ' s core for all classes of heirs (including abstracts) build a data metamodel. To speak the tables in the database.

    There's an interface. SomeInterface

    This interface we celebrate the essence of working with them in a certain way. It's okay.

    But we've got a method of signature. method(Class<SomeInterface> someInterface)Inside of which the nucleus method is used internal(Class<PersistObject> persistObject)

    So to cause this method inside of ours, you have to write something like:

    Class tempClass = someInterface;
    Class<PersistObject> persistObject = (Class<PersistObject>)tempClass;
    internal(persistObject);
    

    I'm the one who's still warning' and ghosts of the types. Huh.

    It would be possible to use some abstract class instead of the interface, which would inherit those classes that are currently being implemented. SomeInterface♪ But as I first noticed, all the heirs. PersistObjectincluding abstracts, they enter the data metamodel. That's unacceptable. ♪

    Is there any way more beautiful? It would be perfect to bring it to the interface that only heirs can handle it. PersistObjectbut I'm not sure java He can.

    upd: There is an option (from comment) to change the signature to a more abstract method:

    method(Class clazz)
    

    Inside check and, for example, fight:

    if(!clazz.isAssignableFrom(SomeInterface.class){
      throw new RuntimeException('');
    }
    

    But I need this method to be called only with this class as a parameter that runs the SomeInterface interface, and that error occurs at the stage of syntaxing the code, not Runtime. ♪ ♪

    That's the option. Even worse. current.



  • The method can be written as follows:

    public static  <T extends PersistObject & SomeInterface> void method(T obj) {
        PersistObject po = obj;
        SomeInterface so = obj;
        //
    }
    

    Then it will be possible to transmit only the exmeptions that are traced from PersistObject and implemented by SomeInterface

    P.S. I'll check it out at the compilation stage, as you need.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2