Reflection: Effective, Awesome, Necessary uses [duplicate] - java

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.

Related

Java extends programmatically

I am wondering about replacing Java's 'extends' keyword somehow for dynamically extending a class based on a parameter(file, environment variable, db...basically anything). Is this even possible because playing with class loaders or calling constructors does not achieve this. I am not asking "should I use interface or superclass hierarchy" rather what is extending really mean under the hood in JAVA because there aren't any good description about it just the good old inheritance jargon:
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The only way to "replace the extends keyword" is to dynamically create classes at runtime, which is entirely possible but non-trivial. Vert.x is a good example of a project that makes extensive use of dynamically-generated classes.
Java wasn't designed as a dynamic language in that sense. There are several dynamic languages out there (some of which can run on the JVM), such as JavaScript.
rather what is extending really mean under the hood...
Without getting into a long treatise on OOP, when you say Derived extends Base, it means that Derived inherits both the public and protected API of Base (which it can then add to) and also the implementation of that API. It means that code expecting to see a Base instance can accept a Derived instance, because Derived "is a" Base. This link is created a compile-time. At runtime, instantiating an instance of Derived involves all of the plumbing that instantiating a Base instance involves, plus then the added plumbing for Derived.
To achieve this you need to maintain various versions of a class based on the condition and you have to customise class loader as well because at a point when you find that you have to load a particular instance, you need to load that class which is not loaded by default class loader on JVM startup.
Its better to maintain multiple versions of the class and let JVM do its job which it does perfectly.
You can't do that with a language like Java. The information about "inheritance" is not only used by the compiler, it is also "hard-baked" into the compiled byte code.
If you really want to such kind of "dynamic" meta programming; you are better of using languages that allow you to do so; instead of "violating" a language that was never intended for such kind of usage.
To use some stupid comparison: just because you happen to know "screws" and "hammer" ... you wouldn't start to use a hammer to get those screws into the wall, would you? Instead, you would be looking for a tool that works better with "screws" than a hammer.
If you still want your code to run within a JVM; you might consider languages like jython or jruby.

Create object dynamically 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.

How to programmatically know who (other java files/classes) is using my java class?

I want to get a list of all java class which are dependent on my class. Is there a library which exposes intended API? API is expected to return list of java classes using my java class.
You would probably use Reflection API..
They were specifically made for this kind of problems.. They allow to get information about classes at runtime..
You can get: -
All the methods
All the derived classes
All the variables.
And many more information..
You can see Class.getClasses() and Class.getDeclaredClasses()
See some more examples
Reflection can tell you whether a specific class extends your class, uses your class as a field, takes your class as a parameter, or returns your class from a method. However if the use of your class is method confined then reflection will not work.

Can a native method call a private method?

I knew that in JAVA "native" is a special thing. It can do a lot of things. But I'm not able to read it right now. I don't know how to... I knew it can call an other mathod in JAVA. My question is: can it call a private method? if it is a YES, then only in the same class or any other classes? if it can call other's, then is it a problem that maybe it's dangerous? that is, it broke the rules. Where can I get more about the NATIVE? can anybody show me a link?
The JNI Programmer's Guide and Specification says this in "10.9 Violating Access Control Rules":
"The JNI does not enforce class, field, and method access control restrictions that can be expressed at the Java programming language level through the use of modifiers such as private and final. It is possible to write native code to access or modify fields of an object even though doing so at the Java programming language level would lead to an IllegalAccessException. JNI's permissiveness was a conscious design decision, given that native code can access and modify any memory location in the heap anyway."
So the answers to your questions are:
Can it call a private method?
Yes.
if it is a YES, then only in the same class or any other classes?
Any class.
if it can call other's, then is it a problem that maybe it's dangerous? that is, it broke the rules.
The designers' rationale for not attempting to enforce the normal Java access rules is clearly stated in the text quoted above. Yes it is potentially dangerous, but any use of JNI is potentially dangerous.
You can call private methods on a Java object that's passed to a native method via the JNI interface. It's not the same thing as within Java, calling methods on other Java objects. You have to be very careful because JNI does not enforce class, field, and method access control restrictions that are expressed through the use of modifiers such as private and final. So it can be dangerous. For example, native code can modify a final constant field of a class, after the JIT compiler has inlined it.
Here's the relevant section of the JNI docs concerning functions and pointers: http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16696

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