How to use Java reflection to set interface field - java

I'm using Jboss 7.1.1.final and i have an application with heavy use of JMS. After doing some performance tests i see that whenever i reach a certain amount of messages the application starts to fail since there are not enough queue sessions.
After some research i discovered that this JMS attribute is only exposed in jboss version 7.1.2 (see here) .
Since, for legal reasons, i can't currently use this version (or the specific build where it was fixed) , the only other way to change it is by using reflection. So i downloaded Jboss source code and started playing with it, now i have a few questions:
First of all i discovered the class i need is org.jboss.as.messaging.CommonAttributes which is actually an interface and it has this line :
SimpleAttributeDefinition CONNECTION_THREAD_POOL_MAX_SIZE = new SimpleAttributeDefinition("thread-pool-max-size",
new ModelNode().set(HornetQClient.DEFAULT_THREAD_POOL_MAX_SIZE), ModelType.INT, true, MeasurementUnit.NONE);
Will ClassLoader.getSystemClassLoader() give me the classLoader i need in order to load the class?
How do i set an interface field value using reflection? (the Field.set() method requires an object instance and since it is an interface i cannot instantiate it)

You are talking about this piece of code. I must disappoint you: interfaces don't have fields, at all. They only have method declarations, without implementation.
What you see there are actually public static final (all these keywords are implicit for "fields" inside interfaces) constants defined within interface body. But the interface is only used as a namespace for them, they aren't real fields. Classes implementing such interface aren't inheriting these fields and having their own variable copy. They are only constants.
That being said - you cannot do anything, at least with this interface.

Related

what is the advantage of using Class.forName() over the new keyword for loading an instance?

I know definition. we use Class.forName("") when we don't know the type of the class but that's the conundrum here.
If I say:
Class.forName("SomeClass");
So I know the type of "SomeClass". So all compiler does in Class.forName("SomeClass") case is does not check whether "SomeClass" exists or not during the Compile time. But it will check it at run time. But is it really the advantage? Can anyone explain this to me with real time scenario?
Class.forName() gives you the class for the given name. It doesn't instantiate it. You could use Class.newInstance() for that (but there are issues with that - see here for more info)
Note that you'd use this in (say) a framework where a configuration file identifies the name of the class you want to load. i.e. that class could be changed at runtime (for example, a Spring XML configuration). In these situations, it's highly likely that your choice of classes would all implement a common interface - otherwise it's difficult for the subsequent code to interact with it.
Class.forName() loads a class that doesn't need to be present at compile time - it just needs to be present when Class.forName() is executed (often class load time, could be runtime as well, depending on where the instruction is specified). This is often the case for, say, database-specific database drivers where implementation classes are provided by the application container and you don't need to care about the instance when developing your app.
An alternative, that would load the class at compile time, would be something like this:
import com.someclass.Foo;
Foo foo; // class would be loaded
However, this is still not an instance of a class that's created with new keyword. Instances are different - if you want an instance, you'd still create with new, irrelevant of how you actually load the class.

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.

Can we list inbuilt Singleton class with proper explanation why these classes require Singleton?

I want to make list of inbuilt singleton classes available in Java and reason for making them singleton.
For E.G.
java.lang.Runtime
Reason: since on whole Java application only one runtime environment can be possible.
java.awt.Toolkit
Reason: AWT needs only a single object to perform the binding and the object is relatively expensive to create
Can we list out all singleton classes in Java?
Well the Java Docs spring to mind. E.G. for Runtime:
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
An application cannot create its own instance of this class.
Can we list out all singleton classes in Java?
Possibly by parsing the HTML of the Java Docs and looking for 'single' or 'singleton'. Though I cannot imagine that would be very robust. AFAIU there is no simple marker for them.
There are allot of Singleton classes in Java., following are few predefined Singleton classes in core Java
1. java.lang.Runtime
2. java.awt.Toolkit
3. java.sql.DriverManager, even implementation of java.sql.Connection interface is Singleton.
There are many more.
Side Note ⇒ Please go though the Java docs online and look for public classes with no public constructors and a parameterless method that returns an instance of it's class. Usually that'll be one.

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...

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

Categories