Skip to main content

How about a genericized class.forname()?

2 replies [Last post]
soupdragon
Offline
Joined: 2006-01-07
Points: 0

As in:

public static Class Class.forName(String fqn, Class superType) throws ClassNotFoundException;

Naturally throws ClassCastException if the class found doesn't implement or extend superType.

Similar could be added to ClassLoader.

This would, at least, be one less inescapable warning message.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
soupdragon
Offline
Joined: 2006-01-07
Points: 0

Alternatively, Class could have an instance version of forName like

public Class loadSubClass(String fqn);

So we could do:

Class cls = MyInterface.class.loadSubClass(plugin);
MyInterface = cls.newInstance();

Without unchecked warnings (and with actual checking).

All that's needed is:

public Class loadSubClass(String className)
throws ClassNotFoundException {
Class cls forName0(className, true, ClassLoader.getCallerClassLoader());
if(!isAssignableFrome(cls))
throw new ClassCastException();
return (Class )cls;
}

soupdragon
Offline
Joined: 2006-01-07
Points: 0

Oh, looks like someone beat me to it:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5030212

I [i]did[/i] search but obviously picked the wrong keywords.