Type safe Class objects (1.5)

When we use Class objects and reflection, we don't get static type safety. For example, after creating a new object by Class.newInstance we have to cast to appropriate type before we use the new object (unless we want to use just the methods of java.lang.Object!). This cast could throw ClassCastException. With 1.5, we can use Class objects with some static type safety. In 1.5, Class object is genericized and so accepts a type parameter. Example below shows typesafe factory usage without coding a "Factory" class as such.

class Main {
   // accept Class object of representing either MyInterface or any of it's subtypes.
   public static void func(Class<? extends MyInterface> clazz) {
       MyInterface intf = null;
       try { 
          intf = clazz.newInstance();  // no cast needed here. 
          // we can assign the result to MyInterface type or any of it's supertypes.
       } catch (InstantiationException ie) { 
          // handle
       } catch (IllegalAccessException iae) {
          // handle
       }       
       // use 'intf' here..
   }
}
Caller of Main.func can use
    Main.func(MyClass.class);
where MyClass implements MyInterface.
Comments:

cAN SOMEONE HELP ME WITH THIS CODE. i AM TRYING TO RUN A BUILD FILE AND IT FAILS. i KEEP GETTING THE FOLLOWING WARNING. cast to java.lang.Object for a varargs call [javac] cast to java.lang.Object[] for a non-varargs call and to suppress this warning [javac] extractor = (Extractor)extractorConstructor.newInstance(new String[] { uri, contentType, namespace });

Posted by John Shappell on December 12, 2006 at 03:23 PM IST #

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder