Here's the code to my previous blog titled "Compiler optimizations may not ...."
ConstantsA.java
package abc;
public interface ConstantsA
{
public static final int CONSTANT_1 = 2003;
public static final String CONSTANT_2 = "Java is good for eBiz";
}
TestConstantA.java
package abc;
public class TestConstantA
{
public static final int CONSTANT_A = 1010;
public static final String CONSTANT_A1 = "Hello_Brave_New_World";
public static final boolean DEBUG = false;
public TestConstantA()
{
System.out.println("TestConstantA's CONSTANT_A : " +
TestConstantA.CONSTANT_A);
System.out.println("TestConstantA's CONSTANT_A1 : " +
TestConstantA.CONSTANT_A1);
if(DEBUG)
{
System.out.println("Debug message. Works only if DEBUG is true");
}
}
public void matchValue(Integer constantA, String constantA1)
{
System.out.println("Value sent by TestConstantB: " + constantA.intValue() +
", Value expected by TestConstantA: " + TestConstantA.CONSTANT_A);
System.out.println("Value sent by TestConstantB: " + constantA1 +
", Value expected by TestConstantA: " + TestConstantA.CONSTANT_A1);
}
public static void main(String[] args)
{
TestConstantA testconstanta = new TestConstantA();
}
}
TestConstantB.java
package def;
import abc.TestConstantA;
import java.lang.reflect.Method;
public class TestConstantB implements abc.ConstantsA
{
public TestConstantB(Integer constantA, String constantA1)
{
try
{
//All this exercise to avoid a direct dependency on
// "import abc.TestConstantA".
//The compiler optimizes the code and replaces all
//Constants with their values.
//If there are no more references to the class being
//imported, it is removed.
Class testConstantAClazz = Class.forName("abc.TestConstantA");
Method matchValueMethod =
testConstantAClazz.getMethod("matchValue",
new Class[] {Integer.class, String.class});
Object testConstantAObj = testConstantAClazz.newInstance();
matchValueMethod.invoke(testConstantAObj,
new Object[] {constantA, constantA1});
}
catch(Exception e)
{
System.out.println("Error occured while using Reflection.");
}
System.out.println("TestConstantA's CONSTANT_A as " +
"perceived by TestConstantB: " +
TestConstantA.CONSTANT_A);
System.out.println("TestConstantA's CONSTANT_A1 as " +
"perceived by TestConstantB: " +
TestConstantA.CONSTANT_A1);
System.out.println("ConstantsA's CONSTANT_1 as " +
"perceived by TestConstantB: " + CONSTANT_1);
System.out.println("ConstantsA's CONSTANT_2 as " +
"perceived by TestConstantB: " + CONSTANT_2);
}
public static void main(String[] args)
{
if(args.length != 2)
{
System.out.println("Usage (Constants will be hardcoded in " +
"compiler code): java def.TestConstantB " +
TestConstantA.CONSTANT_A + " " +
TestConstantA.CONSTANT_A1);
System.exit(1);
}
TestConstantB testconstantb = new TestConstantB(
Integer.valueOf(args[0]), args[1] );
}
}
0 comments:
Post a Comment