简体   繁体   中英

Java how to cast to a generic type

This is my class structure

public abstract class SuperClass

public class A extends SuperClass

public class B extends SuperClass

Now I have a frame which is going to display a list of A elements or a list of B elements, in order not to duplicate code I want to make it the most generic as possible. My idea is to save the class of the elements of the frame in a field:

public class MyFrame extends Frame {
    private final Class type; // type of the elements i'm going to display
    private final DefaultListModel list; // elements to show in a SelectionList

    public <T extends SuperClass> MyFrame(final List<T> elementsToDisplay, Class<T> type) {
         this.list = createListModel(elementsToDisplay);
         this.type = type;
    }

Now it's possible to call smth like

List<A> list = new LinkedList<>(...);
MyFrame frame = new MyFrame(list, A.class);

My problem is how to use the field type , for example when one item is selected in the frame I want to cast it to type class, but I don't know how. The following lines are pseudo-code

<T extend SuperClass> foo(T item) { ... }

// ----

Object selectedItem = list.get(selectionList.getSelectedIndex());
[type.class] castedItem = type.cast(selectedItem);
foo(castedItem);  

How can I cast from Object to the class that is holding type ?

If your goal is really to minimize code duplication by "making it the most generic as possible" (sic), why not do

class MyFrame<T extends SuperClass> {
    private final DefaultListModel list; 

    public MyFrame(final List<T> elementsToDisplay) {
        this.list = createListModel(elementsToDisplay);
    }
}

I would caution you, though, that it's easy to go overboard with your use of generics (especially right after you learn to use them :), and this may well be one of those cases. Also: As a general rule of thumb, any time you find yourself storing the type of a generic class as a field of that class, you should see that as a red flag that you probably need to reexamine your design.

if i proper understand your question the main reason to use generics is to avoid casting i suppose so at your method implementation where you know what type of object you need , you wont use the <T extends SuperClass> but <A> so that certain class will know its generic type to use. if u want to keep the method with <T extends SuperClass> then you have to check the instance of class inside the method and decide which type you ll cast. fe

if( object instanceof A)
 ((A)object).somethinkA();

else if(object instanceof B)
 ((B)object).somethinkB();

else
.....

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