RETRY: Compile-time expressions

T

Timo Kinnunen

I'm reposting this because the eralier post doesn't seem to have
propagated beyong my newsserver.


Now that 1.5 is almost finished is the best time to start thinking
about new features for 1.6. What I'd like to see is a possibility to
force the Java compiler to execute code at compile time and use the
results in the compilation process.

For example, in the following class, methods get1, get3 and get6 just
return an int constant, while the other get-methods produce code to
initialize a static variable and return its value.

The resulting byte code forms seem quite arbitrary. For example, the
get3 and get4 methods should produce identical byte code so that the
choice between them could be made on readability alone.

But instead of adding special conditions to the JLS to make get3 and
get4 identical, I'd like to be able to declare that all values of the
8 get methods are to be precompiled. To achieve this, I propose that
the existing keyword const be changed to mean in the case of:
* primitive variable, that the value of the variable is computed at
compile-time
* static method, that results to all calls to this method are
computed at compile-time.

Any thoughts?


Here's the class:

public class StaticCompilation {
private static final int VALUE1 = 5;
public int get1() { return VALUE1; }

private static final int VALUE2;
static { VALUE2 = 5; }
public int get2() { return VALUE2; }

private static final boolean LOWER3 = false;
private static final int VALUE3 = LOWER3 ? 4 : 5;
public int get3() { return VALUE3; }

private static final boolean LOWER4 = false;
private static final int VALUE4;
static { if(LOWER4) { VALUE4 = 4; } else { VALUE4 = 5; } }
public int get4() { return VALUE4; }

private static final boolean LOWER5 = false;
private static boolean isLower5() { return LOWER5; }
private static final int VALUE5 = isLower5() ? 4 : 5;
public int get5() { return VALUE5; }

private static final int VALUE6 =
(Byte.MAX_VALUE != 127) ? 4 : 5;
public int get6() { return VALUE6; }

private static final int VALUE7 =
Boolean.FALSE.booleanValue() ? 4 : 5;
public int get7() { return VALUE7; }

private static final int VALUE8 =
(new Integer(0).intValue() != 0) ? 4 : 5;
public int get8() { return VALUE8; }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top