Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend Java classes by Reflection?

Tags:

java

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!

like image 696
Koerr Avatar asked Dec 11 '09 09:12

Koerr


People also ask

Can you extend classes in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another.

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

Is it good practice to use reflection in Java?

It is generally a bad idea to use reflection is application code, because you lose the strict type checking of the language. Reflection is generally for use by framework code, where it is essential. Good vs bad are not absolutes, but must be assessed in context.

How does reflection help to manipulate Java code?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


2 Answers

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

like image 198
Bozho Avatar answered Sep 30 '22 19:09

Bozho


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.

like image 36
denis.zhdanov Avatar answered Sep 30 '22 18:09

denis.zhdanov