General J2EE: Is possible explicit cast of objects in java 1.5 ?

  1. Is possible explicit cast of objects in java 1.5 ? (2 messages)

    Hi everybody, Using java 1.5 I have discovered that I don't know how to realize an explicit cast of objects. I have read about generics, but still I don't know how to do an explicit cast in my problem case. Suppose I have a bean class A and a bean subclass B of A. I create instances of classes A and B in main() using static methods of an utility class MyBeanFactory. public class A{ } public class B extends A{ } public class MyBeanFactory{ public static A createAInstance(parameters...){} } In main() I try to create instances of B class using explicit cast, but I always get a runtime exception like java.lang.ClassCastException:cannot convert from a to B.... My code is : B instanceOfB = (B)MyBeanFactory.createAInstance(.....); Please tell how do solve this problem of explicit cast of objects in java 1.5. (I'm using jdk 1.5_07) Best regards, Oana
  2. B is a subclass of A. However, you create an A instance and then try to cast it to B. This is as illegal as creating an Object instance and trying to cast to to a String. Create a B instance, and you will see that it will work to cast it to an A (the reverse, and correct, case). /Niklas
  3. I've encountered a similar issue where I would like to 'cast' or read a method to java.lang.Enum.Modifier: import java.lang.Enum.*; ... Integer _m = Employee.class.getClass().getModifiers(); Modifier _modifier = _m; //illegal Modifier _modifier = (Modifier] _m NOTE: Is it possible to use HTML tags to distinguish code snippets?