class at runtime - java

Is there a way to create Java classes # at runtime
(classes methods n variables), with using Java reflection API

You can't do that using reflection. You need a bytecode manipulation library, like Jakarta BCEL.

The standard Java API provides a set of static methods, that allows you to dynamically create a class that implements one (or many) interfaces.
Those methods are part of the class java.lang.reflect.Proxy.

What do you require this for?
Interpreting the question in a very loose manor I can think of four likely options.
If you have a class that you add something too you might find that Aspect-oriented programming is what you are really after.
If you have an interface that you want to dynamically implement (as posted by barjak) what you want is java.lang.reflect.Proxy. This does not let create "code" at runtime but rather allows you link existing code to to a interface.
Finally (at three I know) you have actually building random classes at runtime. This you will need something like cglib or BCEL. While there are cases when this is required it is IMO rare.
One other option is that you don't really need runtime but rather build time. In this case you might be able to use annotations and apt (Java 5) / Processor (Java 6).

Sure there is. You need a java.lang.Class instance initially, for the target class you wish to create. Depending on your structure, this might either be passed in by a caller (if they're supplying the concrete class they want created), or you can statically access the class variable (e.g. MyFooImpl.class).
The simplest way is to call Class.newInstance(). This invokes the default, no-arg constructor (assuming there is one for the class; if not it throws an exception).
If you need to invoke a particular constructor with some argument, you need to call Class.getConstructor() to get a Constructor instance, which you can then call newInstance on.
In all cases you'll need to deal with reflection exceptions that you wouldn't get if invoking the constructor directly.
Big edit: I assume your question was about creating instances of a class via reflection. However I'm beginning to think that you're asking about defining new classes through at runtime. If so, then reflection won't help you here - you'd need to invoke a compiler programatically, which I believe can be done but I'm not 100% on the details. I think you'd also have to go through some hoops to get the ClassLoader to pick up your new class too.

You can create the source code string and compile it to an class file using Janino.

As people have already mentioned, there's no way of creating new classes at runtime using reflection. One library that I know is used by different mocking libraries and the likes is cglib.

you can use javassist. here is sudo code
javassist.ClassPool pool = new ClassPool(true);
CtClass bclass = pool.makeClass("brandnewclass);
bclass.addConstructor(CtNewConstructor.defaultConstructor(bclass));
CtClass[] fieldclasses = new CtClass[fields.length];
CtClass serClass = pool.get(Serializable.class.getName());
bclass.addInterface(serClass);
Class clazz = pool.loadClass("className");
obj = clazz.newInstance();
Use reflection to extract values from an existing class and assign values to new class.
hope this helps.
Gopi

Related

Can I tell Java to use a class other than Object as default base class?

Assume I find something lacking in the default base class Object, and write a class of my own to use instead.
class MyObject extends Object
{
...
}
Is there a way to tell the Java compiler to use my new class as base class instead of the Object class?
Thus avoiding
class MyClass extends MyObject
and just go
class MyClass
and have it implicitly extend MyObject using, say a command line parameter to the compile
javac MyClass --defaultBase=MyObject
That would mean that all Jars and pre-compiled Class-files would use Object, but anything I compile myself would use my own class, except of course, my new base class. (I wouldn't want a circular dependency, would I.)
You can change the Object class within many limitations, but that not really a good idea. The best solution is to create your own class you want other classes to extend.
If you want to extend Object, the best option is to create a Utility method which takes an Object as an argument.
Is there a way to tell the Java compiler to use my new class as base class instead of the Object class?
No. You can't.
The Java Language Specification (JLS 4.3.2) states that the java.lang.Object class is a superclass of all other classes. If a compiler didn't implement that, it wouldn't be a compliant Java compiler. At any rate, I know of no Java compiler ("compliant" or not) that does allow you to do this.
#Peter Lawrey mentions that it is possible to change the Object class. This is true ... if you know what you are doing. But there are dependencies on internal details of the Object class hard-wired into other class ... and the native code implementation of the JVM. If you change some things (for example, adding instance fields or changing method signatures) you are liable to break the JVM, tools in the Java tool-chain, and/or 3rd-party libraries and tools (like your favourite IDE!). The breakage is liable to be castrophic, and difficult to diagnose.
On top of that, if your change doesn't break Java, you are still stuck with the problem that a real JVM won't run your code. That makes monkeying with Object a viable proposition for "research purposes only" ... at best.
For the record, it is technically possible to override the core classes of the the Java runtime library using the -Xbootclasspath VM option(s) (type java -X to get the info). However, this is not intended to be done by a usual developer (see other answers to this question).
You can try it yourself by modifying and compiling the source of the java.lang.Object to a directory named core-classes, for example, and passing the -Xbootclasspath/p:core-classes as a JVM argument.

Build a Separate Java Class Hierarchy

Every other class in Java inherits from the Object class.
Is it possible to add a second, completely separate, class hierarchy in Java based around my own FastObject class?
My original goal in doing so was to create smaller, faster objects with less functionality specifically designed for certain algorithms. But let me be clear, I am not interested in whether or not this is a "good idea". I just want to know if it is possible; I have not been able to find a way to do so. Would it require a change to the JVM? New boot classpath functionality? Is the real solution to ignore Object and look at replacing java.lang.Class? Would using a direct Java compiler instead of a VM make my job any easier?
To be clear, I don't just want to edit the root Object class. That would require potentially re-writing the entire Java library. I don't want to replace the current hierarchy, I just want to create a separate one I can use in the same code.
No, this is not possible.
All created classes extend another class, either explicitly or implicitly. If you create a class and explicitly define which class it extends, then it extends that class. If not, then it implicitly extends Object. There is no way around this, just as there is no way to overload operators or anything of that sort. It is a fundamental design decision of the Java programming language.
All classes extend Object. The only things that don't are primitive types. The exception to this is Object itself, of course, which does not extend itself.
It may be possible for you to inject your own Object implementation by mucking with the boot classpath. However, I don't think there is any way to use a base object other than Object. You could try some byte code manipulation, but it is entirely possible that your modified class will be rejected by the class loader.

Can a Java class add a method to itself at runtime?

Can a class add a method to itself at runtime (like from a static block), so that if someone is performing reflection on this class, they'll see the new method, even though it wasn't defined at compile time?
Background:
A framework I'm using expects Action classes to be defined that have a doAction(...) method, by convention. The framework inspects these classes at runtime to see what type of parameters are available in their doAction() method. For example: doAction(String a, Integer b)
I'd like each class to be able to programatically generate its doAction() method with various parameters, just-in-time when it is inspected. The body of the method can be empty.
It's not simple. Once a class is loaded by a classloader, there is no way to change the methods of loaded classes. When a class is requested, a classloader will load it and link it. And there is no way (with Java) to change the linked code or to add/remove methods.
The only trick that comes to my mind is playing with classloaders. If we delete a custom classloader, then the classes loaded by that classloader should be deleted or inaccessible too. The idea that comes to my mind is to
implement one custom classloader
load the dynamic class with that custom classloader
if we have an updated version of this class,
remove the custom classloader and
load the new version of this class with a new instance of the custom classloader
I leave that as food for thought, can't prove, if this leads to a solution or if we have pitfalls.
As a simple answer to the question: No, we can't change a loaded class like we can change the content of fields with reflection. (we can't add or remove fields too).
Andres_D is right, we can very well do so using custom class loading, here is a detailed guide on how to do this: http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html?page=1
The article explains how to write dynamic Java code. It discusses runtime source code compilation, class reloading, and the use of the Proxy design pattern to make modifications to a dynamic class transparent to its caller.
In fact researcher in Austria have written a JVM that even allows reloading classes with different type hierarchies. They have achieved this by using existing thread save points to generate a complete 'side universe' of an object and all it's related references and referenced content and then once fully reshuffled with all required changes simply swap in all changed classes. [1] Here a link to their project http://ssw.jku.at/dcevm/ the oracle sponsorship certainly makes for interesting speculations on future plans.
Less intrusive changes to method bodies and fields are already possible in the standard java VM using the Hot Swap capabilities of the JPDA as introduced in Java 1.4:
docs.oracle.com/javase/1.4.2/docs/guide/jpda/enhancements.html#hotswap
I'm not sure whether it was the first one but this Sun employee's paper from 2001 appears to be one of the early proposals mentioning the capabilities of the HotSpot to Hot Swap. [2]
REFERENCE
[1] T. Würthinger, C. Wimmer, and L. Stadler, “Dynamic Code Evolution for Java,” presented at the 8th International Conference on the Principles and Practice of Programming in Java, Vienna, 2010.
[2] M. Dmitriev, “Towards flexible and safe technology for runtime evolution of java language applications,” in OOPSLA Workshop on Engineering Complex Object-Oriented Systems for Evolution, 2001.
I've never tried anything quite like that myself, but you should have a look at ASM, cglib, and Javassist.
No, that is not (easily) possible in Java.
It sounds like you are trying to use Java as if it is a dynamic programming language. For example, Ruby has open classes: you can add and remove methods from Ruby classes at runtime. In Ruby, you can also have a "method missing" method in your class, that will be called when you try to call a method that doesn't exist in the class. Such a thing also doesn't exist in Java.
There is a version of Ruby that runs on the JVM, JRuby, and it has to do very difficult tricks to make open classes work on the JVM.
You can have a doAction method which does whatever you would like the generated method to do. Is there a reason it needs to be generated or can it be dynamic?
It looks like there is no way to add method dynamically. But you can prepare an class with a list of Methods or an hash like:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
public class GenericClass {
private HashMap<String, Method> methodMap = new HashMap<String, Method>();
public Object call(String methodName,Object ...args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method method = methodMap.get(methodName);
return method.invoke(null, args);
}
public void add(String name,Method method){
if(Modifier.isStatic(method.getModifiers()))
methodMap.put(name, method);
}
public static void main(String[] args) {
try {
GenericClass task = new GenericClass();
task.add("Name",Object.class.getMethod("Name", new Class<?>[0]));
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
Than, using reflections you can set or unset the attribute.
I believe you need some byte code altering tool/framework, such as asm, cglib or javassist.
You can achieve this via aspects/weaving like it's done Spring, but I believe you still need to have the method defined first.
Proxy may help. But have to instantiate a Proxy every time you want to add or remove a method.
What I suggest should work for your situation:
1. You have an existing class MyClass with n methods
2. You want to include (n+1) th method which is not in the class while compiling in another .java source file
My way to solve it is Inheritance. Create a new .java source file for a Class MyClassPlusOne extending the first class MyClass. Compile this class and use the object. How can I compile and deploy a java class at runtime?
class MyClassPlusOne extends MyClass
{
void doAction(String a, Integer b)
{
int myNPlus1 = a+b;
//add whatever you want before compiling this code
}
}
I'm not sure that is possible. However, you could use AspectJ, ASM, etc. and weave these methods into the appropriate classes.
The other alternative is to use composition to wrap the target class and provide the doAction method. You would end up delegating to the target class in this case.
This is a rather old question, but I still found myself looking at it today so, just in case, I'll add my two cents.
If you are using Java 8+, you can define "default" implementations of an interface method, so you can just define the interface with all the extra methods with empty default implementations, and add the implements clause in the desired classes. This approach, in some cases, may be the easiest one.
If you don't have control over the definition of the classes, or you need compatibility with older Java versions, you can still define an interface containing all the required extra methods; but in this case, implement a "Decorator" class with a method that receives the object to "decorate" as parameter, and returns a DynamicProxy instance, wrapping the passed object with this interface.
If you are using Spring, the decorator can be added to the context as a #Component, so you can inject it wherever you need to use it. If any of the objects you need to inject are Spring Beans, you could implement a FactoryBean that uses the decorator to return the instances, so you can just forget about calling the decorator explicitly for them.

A Way Of Saying "For All Subclasses In My Project That Extend This Superclass"?

Here's something that's got me a bit stumped but intrigued all the same. In my Android game I have various Levels that extend the superclass Level. What I am trying to do is build a levelDirectory (based on the Singleton DP) that essentially is an object that has a HashMap object within it that stores all the Level subclasses. Here is my question:
We're all familiar with the enhanced for loop, but how can I write something that would be the equivalent of
for(Level l : An Array Of Every Level Subclass In My Project that is an Extension of the Level Superclass){
HashMap.put(l.name, l);
}
I am trying to build a system that can dynamically update itself when I add more and more level subclasses. I know having a method in Level that submitted itself to the static Directory and was called in the Level's constructor is an option, But I'm just wondering whether there is a way of doing what I said above in that enhanced for loop?
Many thanks
The question itself is wrong. You cannot loop over List ("Every Level Subclass In My Project") and get instances of Level. l should be Class.
From the context, I think you meant "every instance of every Level subclass". No, it is not possible - a virtual machine is not and should not be a database. You cannot just query for objects, you have to manage references in your code (but that you already knew that - your constructor solution will work).
Option 1:
Lately I had to solve a similar problem within JavaSE. I'm using the Google Reflections Library for that:
http://code.google.com/p/reflections/
However I'm not sure if it can run with Android. I think it's worth to give it a try, since it's quite easy to use. In your case you would do something like:
Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends Level>> subTypes = reflections.getSubTypesOf(Level.class);
That would give you a Set (subTypes) to iterate on and put it in the HashMap.
Option 2:
You could maybe use custom annotations to annotate your Level classes, for example:
#Level public class MyCustomLevel {}
Then use a custom annotation processor which implements AbstractProcessor to process the annotation at compile time. Implement the process method to find all classes annotated with your #Level annotation. Now you can write the full names of the found classes to a property file in your META-INF dir. From your application you can read this property file and instantiate the classes using reflection.
If you're trying to dynamically fetch the list of all classes that extend Level at runtime, that's not really possible, I'm afraid. Have a look at this thread: How do you find all subclasses of a given class in Java?
I think you might want to make the level an interface and then check if it's an interface.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
void changeCadence(int newValue); // wheel revolutions per minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
I think standard way in the "spirit" of java is the service provider pattern.
Add a declaration file in the META-INF/services of the "plugin" jar and use java.util.ServiceLoader (http://developer.android.com/reference/java/util/ServiceLoader.html) to enumerate your providers.
Don't know much about Android but sounds like Reflection might help here, so what do you know about reflection in Java?
EDIT
Didn't know you had to limit yourself to loaded levels. That being the case you would want to do your tracking on every instance as it is created pretty much like you proposed in your question.
My idea involved parsing all the directories of a project looking for subclasses - it could be done once at the start of program execution but it would list levels that may never get instantiated...

Java, creating interface dynamically?

I'm looking for a solution to create an interface in runtime. I don't really know if this is possible in anyway.
Problem:
I've got a OSGi service which publishes a Map<String,String> where the key defines an action for this service. I want to publish this service directly as Hessianservice with spring but for this, I need to delcare an interface. Now I would like to create this interface at runtime.
It's possible to create interfaces dynamically for example by generating it with a bytecode manipulation library such as ASM. But it won't be possible to use that interface, because no code can be compiled against it (unless you generate dynamically also the code which uses it).
What is it that you are trying to do?
You can't really do that (unless you involve byte-code maniuplation/creation and I don't think that's the best path).
What good would a dynamically created interface do if you have nothing that could access that interface?
Or in other words: nothing can compile against a dynamically created interface (since it doesn't exist at compile-time, obviously). So who would be using it?
Picked the following answer from another question. The example actually writes a new class, so may be this will help you.
JDK6 has a Java compiler API. However, it's not necessarily very easy to use.
A quick google pulled up this example usage.
Interfaces and classes exist solely to help compilers find possible bugs. If you want to make this interface at runtime, you have no compiler, co it won't find you the bugs, so why do you need this interface?
In such a situation just publish implementation of some generic interface, which can look like:
interface GenericInterface {
Object invokeMethod(String name, Object... arguments);
}
That's the only interface you need, and you can create it at compile time! Only implementations of it you may need to create at runtime, eg with java.lang.reflect.Proxy

Categories