Create object dynamically java - java

This may sound like a silly question, however i am trying to test my game under different circumstances using reflection. I was wondering if their was anyway to dynamically create an object to contain certain methods, i know i can use proxies, but then i am limited to the methods declared in the interfaces i choose to use in the proxy so i have to create a new interface for each thing i want to add to my object that i am creating. I am hoping to access each method using reflection. I know there are libraries that do this so i am sure that this is possible and i am hoping to not have to install libraries, as i will have to deal with a new api.

In languages like C, you can pass function references as parameters to another function or procedure. Is this what you are referring to? You want to pass a reference to a function to a method about which the method may not have advance knowledge?
You can't pass function references as a parameter in Java. It isn't allowed. But the workaround for this is exemplified by the abstract factory pattern. This pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Related

Why new keyword considered as high coupling in Java?

I am working on Java for some time. I saw there are too many talks about decoupling the objects. I see they say "new" keyword is considered as symbol of high coupling. I did not get any answer till now why it is. can anyone explain me?
Well new creates an instance of a specific class. So whenever you use new you are creating coupling between the class being created and the code that creates it. Example:
List<String> strings = new ArrayList<>();
creates an instance of ArrayList, which is a problem if you don't need to hard-wire the code to use that specific implementation of the List API.
Note that Java new doesn't allow you to make the class name a parameter. Not even with generic type parameters.
The alternative is to use a factory function or object, or use dependency injection to decouple the code that needs the instance of a class from the procedure that creates it. (Or pass around Class objects as parameters and use reflection to create instances.)

Java: How to listen on methods invocation without registering each object explicitely?

I want to listen on method calls in order to attach additional behavior dynamically around the call. I've already done it on JUnit methods with a custom annotation and runner. I'm trying to do it on a standard java application.
The main idea is to do:
#Override
public void beforeInvoke (Object self, Method m, Object[] args){
Object[] newargs = modifyArgs (args);
m.invoke (self, newargs);
}
It's just an abstract idea, I don't have any concrete example, but I'm curious if it's possible in java.
I've found some approaches:
java.lang.reflect.Proxy.newProxyInstance(...)
where a proxy is defined for an interface only (but not used to decorate concrete classes). It seems similar to injection pattern and it's a different concern.
Another approach here using a factory pattern with the ProxyFactory class. This other solution requires explicit calls to create() method to produce object proxies listening on method invocations. So, if you bypass it by using natural constructors of your classes, it's not working. It's very constraining if you must explicit a call to a factory each time you have to create an object.
There is a way to do it with transparency ?
Like Proxy.newProxyInstance() but working also on concrete classes ?
Thanks.
Well,this is commonly seen with Spring Framework and Aspect Oriented Programming. Since you delegate your constructor calls to Spring, it is quite easy for Spring to put a proxy in place to intercept calls to the actual objects.
As far as I can tell, the only way to intercept calls is to use a proxy. Either in the way you mentioned or using Spring and AOP.
I think cglib let you instrument concrete classes.
As far as I know there is no easy way to intercept method calls that are called on a concrete class.
As mentioned you could manipulate the bytecode during compilation (as Used in AOP) or at class loading time (as used from cglib).
Another product to instrument Classes would be jmockit (http://jmockit.org/). Usually I would use this special kind of black magic only in testing environments and not in an productive environment.
Another way you could go is Annotation Processing. It work's during compiling process. You have to write a Processor which will walk through your source code and generate source-code that contains the original code plus the enhanced method-calls you need.
Depending on how much source-code you have to enhance, this method might be a good idea, but in general it is a lot of work.
Here's a link (https://deors.wordpress.com/2011/10/08/annotation-processors/).
Despite usually it's used in combination with annotations, this is not a strict requirement.

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.

class at runtime

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

Reflection: Effective, Awesome, Necessary uses [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
What is reflection, and why is it useful?
So I've read the Reflection tutorial on Java's website, and I think I generally understand that it allows a class to inspect itself, having access to properties, methods, etc. However, how, if at all, does this relate to mutable or immutable code? Can classes change their own code using something like reflection? If not, what's the most awesome use of reflection you've come across/created?
Thanks!
No, reflection does not directly enable a class to change its code. However, there are some awesome things you can do with java.lang.reflect.Proxy - e.g. write generic code that implements any JavaBean-style interface (i.e. set and get methods), or even code that implements any interface by having all methods return default values - possibly even recursively, i.e. methods that return an interface type return an object that behaves in the same way.
This facility is used by Mock object libraries, and probably most prominently by the Groovy language to implement a fully dynamic language that supports duck typing and monkey patching.
Java reflection does not allow you to dynamically change the code of the program like you would be able to in a dynamic language such as ruby.
Java reflection allows you to see meta data regarding methods and properties of a class. It also allows you to call those methods or to change values of properties, without having prior knowledge of the methods and properties available.
To modify program code at runtime in Java, have a look at Aspect-Oriented Programming.
The most awesome use i've seen is in the JRuby bindings, to make Java classes dynamically available as ruby code. I've also used reflection myself to allow me look up error codes from a third party library that was using static int Constants instead of enums.

Categories