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
2010-03-11 19:28:08
thanks, I tried it and it gives the name with the package, e.g package.subclass
Halo
2010-03-11 19:29:02
you can also use instanceOf......
erasmus
2010-03-11 19:33:05
+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");
}
}
}
Pierre-Antoine LaFayette
2010-03-11 19:28:54
yeah it's probably a design flaw :) But I don't know, there seems to be no other way to do this.
Halo
2010-03-11 19:33:26
http://www.javapractices.com/topic/TopicAction.do?Id=31
Pierre-Antoine LaFayette
2010-03-11 19:36:01
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
2010-03-11 19:56:21
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
2010-03-11 20:29:23
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
2010-03-11 20:41:57
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
2010-03-11 22:06:00