views:

44

answers:

2

I have this object which is an instance of a superclass. I want to know which subclass that object really is, so that I can decide what to do with it. There is this getClass() method but it's apparently not used for comparison issues. How can I get the sub-type of my object?

+1  A: 

Class c = (your super class name).getClass();

if(c.getName == "your sub class name") take action

erasmus
thanks, I tried it and it gives the name with the package, e.g package.subclass
Halo
you can also use instanceOf......
erasmus
+1  A: 

You may have a design flaw if you're trying to do this but instanceof.

public class MainClass {
  public static void main(String[] a) {

    String s = "Hello";
    if (s instanceof java.lang.String) {
      System.out.println("is a String");
    }
  }

}

See Beware of instanceof operator.

Pierre-Antoine LaFayette
yeah it's probably a design flaw :) But I don't know, there seems to be no other way to do this.
Halo
http://www.javapractices.com/topic/TopicAction.do?Id=31
Pierre-Antoine LaFayette
hmm. how can this apply to MVC, then? I mean, my model does not know about the view, so I can't use polymorphism to create the appropriate components in the view. How am I gonna do that then?
Halo
I'd have to see the code to know what you mean. You may be misusing inheritance. Remember to favor composition over inheritance.
Pierre-Antoine LaFayette
Maybe I can explain this way: The model has the coordinate and drawing info, and View is going to create the components, then the Model will draw inside the component. But I can't have one type of component, I need JPanel, JTextArea.. depending on the model element type. I couldn't decide this in the Model cause it would be GUI in the model. And the View can only decide by the model element's type. Hope that makes sense, but it's a little messed up I must agree.
Halo
I think your components are really supposed to be your views.Check out this good overview: http://java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html#JFCMVC
Pierre-Antoine LaFayette