Search code examples
javafunctionparentextends

Pass unknown class extending parent, then call functions of parent (Java)


I know that all classes passed to the function will be extending JComponent, but I don't know what the classes are themselves.

My code is specific, but what I am asking is more general. In my code I am attempting to pass an unknown class that extends JComponent for the purpose of calling the JComponent method of setFont() on the class.

I have written this up as:

    public void setCustomFont(String ttfFile, Class<? extends JComponent> jc){
      try {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(ttfFile)));
      } catch (IOException|FontFormatException e) { e.printStackTrace(); }
      jc.super.setFont(Font.TRUETYPE_FONT);
    }

jc.super.setFont( gives the error: jc cannot be resolved to a type

while ((JComponent) jc).setFont( gives the error: Cannot cast from Class<capture#1-of ? extends JComponent to JComponent>

and finally jc.setFont( gives the error: the method setFont(int) is undefined for the type Class<capture#1-of ? extends JComponent>

So, I honestly cannot figure out how to call functions of a parent through the child passed to a class.


Solution

  • You don't need to pass the class to the function.

    Just pass the object itself:

    public void setCustomFont(String ttfFile, JComponent jc){
        ...
        jc.setFont(Font.TRUETYPE_FONT);
    }
    

    The setFont method is not a class method, it's an instance method, so you need an actual object that implements JComponent in order to call the method.

    By defining the parameter as JComponent jc, the method will only accept objects that extend from JComponent, without knowing the specific class.