Java : Final oddity

Hey, I’m back.

I was captured in optimization facts lately and I ended up chasing the true advantages in using final stuff correctly (in Java of course). But much before I could state I have an opinion, I found myself trapped in a strange JVM… mystery.
What I wanted to understand is if the JVM can listen to our ‘hints’ to take the final stuff  and use it inline.
This topic has been subject of many talks, mostly because it’s hard for the JVM to determine whether a field won’t change at runtime or not. This could be obvious at first sight: final fields won’t change. But when reflections come into play, well… you’ll never know.
So can reflections change a final field? This is the question. And the answer is: WHO KNOWS? If you look at this document, you’ll notice it’s a long and painful story.

Since there’s nothing better than trying stuff yourself, I tried to discover it by doing a simple test program.

public class Malicious {
	public final int testField = 5;

	public static void main(String[] args) throws Exception{
		Malicious m = new Malicious();
		Field f = m.getClass().getField("testField");
		f.setAccessible(true);
		f.setInt(m, 7);
		System.out.println("f: "+f.getInt(m));
		System.out.println("m.testField: "+m.testField);
	}
}

Before I tell you the results, let me first say that I used:

- MacOSX 10.6.4
- 1.6.0_22
So you won’t get upset if you get different results on different environments.

RESULTS:
f: 7
m.testField: 5

Honestly, this makes no sense. No security exceptions, nothing, just different values. And of course, if I remove the final keyword, what I get is:
f: 7
m.testField: 7

I’m honestly happy to state that a final field cannot be modified via reflections. I’m less happy to say the behavior is not supported by a homogeneous communication because I only got a security exception when I tried to remove the setAccessible line.

Trick: Invoke methods with varargs

Two days ago I faced a strange situation:
Java: let’s say you have a main function (that, as you all know, accepts varargs arguments) and want to use it as a gateway for other main functions. You don’t want to specialize the gateway, so that it will work for any new subprogram your jar will have added. The gateway will receive, as first argument, the subprogram class name.
The first thing to do is easy:

 Class c = Class.forName(args[0]);

Next, we want a Method object for the “main” function:

Method mainMethod = c.getMethod("main",String[].class);

Next, we want to invoke the method but the thing shows up trickier than expected, because if you:

mainMethod.invoke(null, args); //NOT WORKING

Nope, nada. Why? Because the args you’re passing would be splitted in single arguments, that IS NOT what the function is expecting. In fact, “main” wants a “varargs”. That sounds like a nonsense, but varargs is in fact a little naive…
To workaround this:

Object o = args;
mainMethod.invoke(null, o); 
and there you go. This was not hard to solve, and thinking of it a little, it looks quite obvious, but the runtime error you get doing it the wrong way is a little too tricky, so I wanted to share this with you.
Peace

Good annotations: clean code

Annotations are a fantastic tool introduced in Java 1.5 that allows you do add some extra information to a class, method or field.
I thought of it lots of times, but I’m sure we all did: a class is a class, it does its stuff, it has its fields and methods, but it would be nice to add some extra information to trigger some events, in certain conditions. I mean, not variable, mutable, changeable info, just static stuff.
Let me do a very simple example. Image a stupid javabean dump function. It gets a generic bean, and prints the values returned by the getters (with the technique I explained in “Coffee Mug Reflections part 2″)

class RandomBean{
[...]
public int getAVal();
public int getBVal();
}

The function we’re talking about would print the results of getAVal and getBVal. Say, “1″ and “2″? Meaningless data. Even if we printed the methods name “getAVal: 1″ and “getBVal: 2″: useless. Even if the function name were “getArctanOfC”, the list of methods would be almost useless. How can we associate a comment to methods? Let’s annotate it!

Read more of this post

Coffee mug reflections part 2 – Method objects

I’d like to spend a few words about Method object for many reasons. First, they’re cool. Second, if you come from the C/C++ world, you might have had the feeling that something was missing: function pointers.

In C/C++ function pointers are extremely handy tools to do lots of nasty stuff, and I must admit, before this was available in Java, I felt like something was missing.
Method objects are slightly different from function pointers and what I can say is… they’re way cooler. But before we have a look at how to use it, let’s proceed my way.

***Add on 2009/03/12 – thanks to Walter Milner***
What exactly is a Method object?
When you write a method, you rarely stop thinking about what exactly is the act of writing one. You’re writing a procedure that can freely interact with the object it’s enclosed in. In the method body you (and the compiler) make some some assuptions like:
when you write a=10; the compiler assumes that a is accessible from the method and that it’s a int. That’s obvious to you, but you shouldn’t ignore the importance of this fact. If a is private, nothing but the class methods are able to access its value. So your method is privileged.
A method object is an object that can trigger a method, knowing the class in which it’s defined, its name, and its parameters (in other words, its signature). The method can be static -and in this case it has no reference class- or not, and in this case you have to tell the method what class it’ll be reflecting on. If the method object changes the value of the class field a, you must let it know which object you want to alter.
Example:

class Stuff{
  private Integer a;
  public void setA(Integer val){
      a=val;
   }
}
//[...]
//...main...
Stuff first = new Stuff();
Stuff second = new Stuff();
//here's my reference
Method m = Stuff.class.getMethod("setA",Integer.class);
//I apply it to second
m.invoke(second,10);
//guess what's the value of a in second object...

***

Why the heck would I ever need them?
I can agree with you in some ways. There are very few things you can’t do in Java without them. One of them is the example we’ve seen in the previous chapter of this series. In that occasion we’ve used methods we didn’t even know they were there.
Another interesting setup is: method objects gives us a very fluent way to run methods or sequences of methods we choose runtime. Want an example of this? Say, image processing. A BufferedImage and a stack of things to do to it, build by a configuration file? You can do it traditionally? Alright, imagine now that everyone can produce a filter class ( extends ?) with only two rules: (1) each filterng method gets at least a BufferedImage and returns a BufferedImage (transformed); (2) every extra parameter is a java.lang type. This is getting a little tricky. Now, I agree with you this example is way too extreme, but see how the boundries of things you can do, change dramatically with this technique in your hands?

Read more of this post

Coffee mug reflections part 1

You might not be that hardcore programmer to be a fan of it, but you certainly have at least heard about Java reflections.

This technology is available since Java 1.3 and it help us to do something extremely cute and, in some cases, tremendously useful.
It allows us to inspect the contents about classes and objects, without really know what class or object we’re handling. In fact that’s what it does: I don’t know you, so I ask you to tell me how you’re done.

I don’t like overwhelming theories, facts count, and as far as you understood the previous paragraph, you’re ready to read some examples. Let’s start with the very basics.

Read more of this post

Follow

Get every new post delivered to your Inbox.