简体   繁体   中英

Using methods with returned jcomponents and generics

This is a two part question. First, is it possible use a generic defined objects method such as:

public class MyClass<T>{

    public MyClass(T t){
        t.setText("Hello World"); // Assume class T is JMenuIten has the special method setText
    }

}

This code doesn't work as is, but show the general idea for what I'm aiming for. I want to use the methods which are particular to that encapsulated object. If however I were to pass in another object such as which contains the encapsulated method .doSomething. I would like to do ...

public class MyClass<T>{

    public MyClass(T t){
        t.doSomething("Hello World"); // Assume class T is JMenuIten has the special method setText
    }

}

I'm hoping that it is possible to do this, otherwise I would have to write multiple constructors to take care of all my special cases.

My second question is similar in that I would like to return a GUI component and execute a statement such as ...

myJPanel.getComponent(1).setText("Hello"); // Assuming index 1 is a JLabel and setText is a specific method defined in the JLabel class

This code does not work because the compiler cannot tell ahead of time what symbols will be needed at runtime, though I was hoping that there was a way of making things like this work. I would also like to know if there is a method that can tell me what class type .getComponent() is returning if that is possible. I'm trying to make code as dynamic as possible without having to hardcode everything.

Thanks

You have to use a bounded wildcard.

eg

public interface MyObject {
    void myMethod();
}

public class GenericObj<T extends MyObject> {
    private T t;

    public void invokeMethod() {
        t.myMethod(); //this way you can invoke methods (declcared in MyObject) on T
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM