java force an extending class

前端 未结 6 1349
梦毁少年i
梦毁少年i 2020-12-31 00:17

In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public          


        
6条回答
  •  清酒与你
    2020-12-31 00:31

    Probably there it's not possible at compile time, but you can use reflection to check at run time if the desired constructor was declared:

    public abstract class Points {
    
        protected Points() {
            try {
    
                Constructor constructor = 
                    getClass().getDeclaredConstructor(Object.class);
                if (!Modifier.isPublic(constructor.getModifiers()))
                    throw new NoSuchMethodError("constructor not public");
    
            } catch (SecurityException ex) {
                throw new RuntimeException(ex);
            } catch (NoSuchMethodException ex) {
                throw (NoSuchMethodError) new NoSuchMethodError().initCause(ex);
            }
        }
    }
    

提交回复
热议问题