tags:

views:

218

answers:

5

I have two Strings:

String a="org.test.A";
String b="org.test.B";

I get a class by Reflection

Class aClass = Class.forName(a);

I want aClass extends b, like:

Class okClass=aClass.extends(b);//how to implement this?

how to implement this?

how to get okClass?

thanks!

+3  A: 

You could start by reading up on dynamic proxies. Proxies do not extend classes, but they do implement interfaces which you can map on your class implementation through the invocation handler.

rsp
+5  A: 

Apart from using a JDK dynamic proxy, which works only by interface, you can use CGLIB or javassist for extending classes at runtime.

Bozho
+4  A: 

Generally speaking you want to be able to create new classes (not objects) at runtime. You can use bytecode engineering or java compiler api for that.

denis.zhdanov
A: 

As said before I'd recommend to look at CGLIB but there is also javassist which is a class library for editing bytecodes...

pgras
A: 

I'm not sure I understand entirely what you're asking. In this case, A and B already have an implementation. Class.forName() looks up a class by name from the classloader and adds it to the PermGen. You're getting a reference to the class itself, but not a new instance of either class.

Are you trying to ask how you may know if B extends A? If so:

Class a = Class.forName("org.test.A");
Class b = Class.forName("org.test.B");
boolean extends = a.isAssignableFrom(b);
Brian M. Carr