Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to Unknown Type When Only Given Class Name as a String of That Type

I currently posses a List of Objects(Using Java 1.3), and let's say that I wanted to cast one of the Objects returned from list.get(i) to a type of which I only know the name of the Class as a String. Essentially, how do I Object o = (classname)list.get(i); where className is a String variable of a className.

I thought that I could use ( Class.forName(className) )list.get(i), but I received a syntax error claiming that I forgot a semicolon.

Unfortunately, since I am using Java 1.3, I do not have access to the Class.cast(Object) method.

What is the name of the class used when casting to another type in Java 1.3? Is there some method that can give me the correct type I need with a String parameter of the class name?

like image 414
Paradius Avatar asked Jan 26 '09 18:01

Paradius


3 Answers

what is the point of casting when all you do is assign the result to object? All you would achieve is an exception if it did not implement the interface/extend or was the class or do nothing if it did.

For that a simple:

  public static boolean IsInstance(object x, String className)
  {
     Class cls = Class.forName(className);
     return cls.isInstance(x);
  }

is sufficient (and cleaner)

If you were to the use reflection to get at the fields/methods of the class that's just fine

like image 156
ShuggyCoUk Avatar answered Oct 17 '22 22:10

ShuggyCoUk


No, and you can't do this across most languages.

The reason is that the type to cast to has to be known at compile time, not at runtime (which is what you are trying to do).

If you think about it, it makes sense, because given that the variable could be any type name, how are you supposed to access the various members? You can't, not unless they are defined in a base type/interface that all instances implement, in which case you should just use that.

like image 28
casperOne Avatar answered Oct 17 '22 23:10

casperOne


One scenario where the need for this arises is when enforcing type safety with a legacy system. For example, suppose you have a persistence system like Hibernate that provides a raw List of results from a "finder" method. Casting this raw List to a parameterized type will result in an unchecked warning, and if the List contains an object of the wrong type, a ClassCastException can be raised at an unspecified time in some distantly related code. It may be best to validate the contents of the list up front, using a mechanism like the OP suggests.

Here's the Java 1.3 version (without generics):

private static void checkType(Collection objs, String className) 
  throws ClassNotFoundException
{
  Class clz = Class.forName(className);
  Iterator i = objs.iterator();
  while (i.hasNext()) {
    Object obj = i.next();
    if (!clz.isInstance(obj)) {
      throw new ClassCastException();
    }
  }
}

In Java 5 and later, with generics, you can do something similar with the Class.cast() method to verify the contents of a collection, justifying the use of a SuppressWarnings annotation. In our review process, suppressing a warning without some "proof" that it is safe is filed as a bug.

like image 2
erickson Avatar answered Oct 17 '22 21:10

erickson