Search code examples
javaclassruntimeextend

Extending a class at runtime


I need to create a custom table UI. For future flexibility I would rather extend whatever object is returned by the call to UIManager.getUI() at the end of JTable.updateUI(). So, I can't know what the class is called, or its path, until runtime.

Is this possible and how would I do it? I've never done anything to do with reflection, so if it involves that, please be gentle with me :-) I've had a look at other similar questions here and none of them seem to be what I need, or in an understandable way. Sorry if I've missed something :-)

Edit: the structure I assume I'll need to use is something along these lines (this will go in my JTable descendant):

@Override
public void updateUI()
{
  super.updateUI();
  ComponentUI theUI = UIManager.getUI(this)[extended in some way with an overriding paint(){....}]
  setUI((TableUI)theUI);
}

It's the syntax for the part in square brackets that I'm missing. What's in my mind is something kind of like the anonymous inner class declaration, perhaps:

...
ComponentUI theUI = UIManager.getUI(this)
{
  public void paint(Graphics g, JComponent c)
  {
    ...
  }
}

I'm not saying the above exists, but is there some way to achieve it?


Solution

  • if this is what you meant:

    you can load a class at runtime using Class.forName. example: say we have an interface A which defines functiong foo() with many classes implementing it. It's important to have same constructor for all of the classes (can do without it but it will be much complicated logic)

    at runtime we get the name and possibly path (or we already know where our class should be by some other mean) of the class we want to use. so we can go like this:

    String class = getPath();
    Class<?> toUse = Class.forName(class);
    A instance = (A) toUse.getConstructors()[0].newInstance(args);
    instance.foo(); //TADA
    

    after op edit: ok your question is more clear now and I doubt my solution is what you're looking for. You can maybe create a class that will compose ComponentUI and use it to extend whatever you need.

    something like this (really not sure if it helps since I have no knowledge about this whole JPanel etc thought this question was a mroe general one at first):

    class B { //maybe class should extend or implement something, depends on what exactly is required
           private ComponentUI c;
           //other fields
    
           public B(ComponentUI c) {
               this.c = c;
               //other stuff you need done
           }
    
           //other methods you might need
    }