I'm learining Java reflection API. I have read a lot, use java.lang.reflect package.
But there is still something I don't understand : the idea that with introspection, you can modify objects at runtime.
Basically you do not need introspection/reflection to do that. With a simple setter() method, you can also modify your object at runtime. What's the difference between using simple setters or using reflection ? In both cases you can achieve the same result.
With reflection you can instantiate objects and call methods that you didn't know about at compile time.
Imagine you had a text file that contained the name of a class. You can use reflection to load and instantiate that class, even if that file didn't exist when your program was compiled.
Similarly, you can use it to build things like generic configuration systems where you create objects and set properties based on some configuration files instead of using hard-coded calls (Spring is one way this can go).
Related
From wikipedia:
reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.
Can anyone give me a concrete example of modifying the structure of an object? I'm aware of the following example.
Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);
Other ways to get the class and examine structures. But the questions is how modify is done?
Just an additional hint since the previous answers and comments answer the question concerning reflection.
To really change the structur of a class and therefore its behaviour during runtime look at Byte code instrumentaion and in this case javassist and asm libs. In any case this is not trivial task.
Additionally you might have a look at aspect programming technic, which enables you to enhance methods with some functionallity. Often used to introduce logging without the need to have a dependency of the logging classes within your class and also dont have the invocations of the logging methods between the problem related code.
In English reflection means "mirror image".
So I'd disagree with the Wikipedia definition. For me, reflection is about runtime inspection of code, not manipulation.
In java, you can modify the bytecode at runtime using byte code manipulation. One well known library and in wide spread use is CGLIB.
In java, reflection is not fully supported as defined by the wikipedia.
Only Field.setAccessible(true) or Method.setAccessible(true) really modifies a class, and still it only changes security, not behaviour.
Frameworks like e.g. hibernate use this to add behaviour to a class by e.g. generating a subclass in bytecode that accesses private fields in the parent class.
Java is still a static typed language, unlike javascript where you can change any behaviour at runtime.
The only method in reflection (java.lang.reflect) to modify object's class behaviour is to change the accessibility flag of Constructor, Method and Field - setAccessible, whatever wiki says. Though there are libraries like http://ru.wikipedia.org/wiki/Byte_Code_Engineering_Library for decomposing, modifying, and recomposing binary Java classes
I am reading an Excel file using java, I have written some methods for my business logic and i want to implement using properties File.
What i want to Do is :
I am having 10 Columns and 10 methods, i need to declare this methods in Properties file use from that file.
Suppose for column A i want only 2 methods then i can use only those 2 methods, For next column B suppose 10 methods and So on.
Can i Do this or is there any other way to implement this.
Please Suggest me if there is any other way to implement this. Thanks in Advance.
To prevent misunterstandings: properties files are just text files, so you need to use Java code in order to process them. They'll only provide a String->String (key->value) mapping, thus you need to parse and interpret the strings yourself.
That being said, here's a suggestion on what you might (want to) do:
Since your question isn't that clear I'll make a couple of assumptions:
Your properties file contains something like:
column1=method1,method7
column2=method1,method2,method3
etc.
The methods are all declared in one class using a common signature
When parsing your excel file you might want to apply the methods to the columns based on the properties file.
So, here are some hints on what you could do:
Parse the properties file and create a list of method names per column
When working on a cell/column get the method names for the respective column
Use YourClass.class.getMethod(methodName, parameterTypes) to get the Method instances.
Call Method#invoke(...) to invoke the method.
Edit:
As an alternative to having all methods in one class you could also use the fully qualified class name, e.g. yourpackage.YourClass#method1, split at # to get the class name and the method, then use Class.forName(fqcn) to get the class and finally call getMethod(...) on that.
If the signature differs, you might have to use a more complicated notation and parse the parameter classes as well.
There be parsers ready to use for this, but I don't know any. However, some apache commons projects like El and Configuration might prove useful for this task.
It's not at all clear what you are trying to do, but in any case you definitely cannot "call" any Java methods from a .properties file (or call from Java to a method contained in a .properties file). A .properties file is not executable, nor is it treated by any standard Java utility as executable/interpretable code. In essence, all it contains is data, and data cannot call or be called.
What you could do however is roll your own framework for doing this, either by using reflection to map the textual method calls in your input file to actual method calls against one or more Java objects, or more simply (but less flexibly/extensibly) by storing a predetermined set of codes which you map directly to method calls using a switch/if-else block, or perhaps by storing your desired code as JavaScript and using an existing Java-based JavaScript interpreter to execute the code.
I am working on an application that hosts user defined stored procedures that are provided as Java class files. The procedures need to be deterministic, and I want to black list various packages and methods that are sources of non-determinism. I have looked at what is available in java.lang.Class and javax.tools.*.
It looks like I can audit members, method parameters, and return types using java.lang.Class. However to audit the method contents it looks like I would have to analyze the raw class file.
There also corner cases like static intitialization blocks and member variable intialization that I need to audit. There are cases like java.util.Date where the default constructor is non-deterministic, but the others are fine.
Is there a framework or tool that would make analyzing these aspects of a class file easy?
Yest there is. As you say to 'analyze these aspects' use e.g. AspectJ ;) You can use load-time weaving with javaagent for example. Another way is to load users' classes with aspectj classloader.
You can declare poincuts looking for given method invocations. You can also enclose users method and count execution time and so on.
Is there any way we can inject new methods and properties into classes during run-time.
http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.html states we may do that by using Groovy.
Is it possible by just doing using Java?
Is it possible by just doing using
Java?
The simple answer is an emphatic "You don't want to do that!".
It is technically possible, but not without resorting to extremely complex, expensive and fragile tricks like bytecode modification1. And even then, you have to rely on dynamic loading to access the modified type and (probably) reflection to make use of its new members. In short, you would be creating lots of pain for yourself, for little if any gain.
Java is a statically typed language, and adding / modifying class type signatures can break the static typing contract of a class.
1 - AspectJ and the like allow you to inject additional behaviour into a class, but it is probably not the "runtime" injection that you are after. Certainly, the injected methods won't be available for statically compiled code to call.
So if you were really crazy, you could do something like what they outline here. What you could do is load the .java file, find the correct insertion point, add whatever methods you need to, call the java compiler and reload the class. Good luck debugging that mess though :)
Edit This actually might be of some use...
You can do some quite funky things with AOP, although genuine modification of classes at runtime is a pretty hairy technique that needs a lot of classloading magic and sleight of hand.
What is easier is using AOP techniques to generate a subclass of your target class and to introduce new methods into this instead, what AOP called a "mixin" or "introduction". See here to read how Spring AOP does it, although this may be quite lame compared to what you're actually trying to achieve.
Is it possible by just doing using Java?
Quite so, the "only" thing you have to do is define an instrumentation agent which supplies an appropriate ClassFileTransformer, and you'll have to use reflection to invoke the added methods. Odds are this isn't what you want to do, though, but it's doable and there's a well-defined interface for it. If you want to modify existing methods you may be interested in something like AspectJ.
While it might be possible, it is not useful.
How would you access these new fields and methods?
You could not use these methods and fields directly (as "ordinary" fields and methods), since they wouldn't be compiled in.
If all you want is the possibility to add "properties" and "methods", you can use a Map<String, Object> for the "dynamic properties", and a Map<String, SuitableInterface> for the "dynamic methods", and look them up by name.
If you need an extension language for Java, an embedded dynamic language (such as Javascript, or Groovy) can be added; most of these can access arbitrary java objects and methods.
Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.
I know the .NET framework mbUnit has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).
Clarification: I could definitely build something like this. I was asking if there was anything out there that already enabled this.
Based on your last paragraph, what you're trying to do is inject some 'extra methods' into unit testing since you're already testing a specific class. I do not know of a testing harness that allows you to attach tests based on the hierarchy of a class.
However, with your own suggestion of using TestNG for building something similar, I think you might be very close. You could very well incorporate some base code that adds your class to a list of 'default test classes', which are in turn tested if they implement a specific interface.
Still, regarding the general case, I think you're out of luck, since the Java type system is one-way, you can only (easily) find out what interfaces a class implements, not the other way around. Furthermore, the problem is 'where to stop looking': if you have a test that checks all your comparable implementers, do you want it to check the validity of String's one too, since that is in your Java environment?
Try this
http://www.xmlizer.biz/java/classloader/ClassList.java
In .NET it would be pretty simple to set up a method that looks through an assembly and identifies each class's inheritance/implementation hierarchy. I'm sure you could do it in Java, too, if you research the Java reflection API.
You could then create an array of ITargetInterfaces and call a test method on each one.
One way would be to search through the jar file for all the .class files (or search through the classes directory), use the Class.forName() method to load the class file and check MyInterface.class.isAssignableFrom(myClass).
This wouldn't deal easily public inner static classes (you could parse the class file name), but would never work with private inner classes or anonymous inner classes.