Simulating C/C++ empty defines in Java - java

I know Java does not have pre-processor, but I struggle to find a way to do this.
I am looking to create macros to improve code readibility, to specify which of the functions or parameters are for input or output specifically. In C, this would be done like this :
#define IN
#define OUT
And these would just be used before the variables and functions. Can I simulate the same behavior in Java?
I did not manage to find a way to do this. The only way I found was including defines in the code and first using the cpp pre-processor to replace them, and then run the java code, but maybe there is a better way of doing this?

Java indeed does not have a pre-processor, and your use case doesn't require that either: you aren't actually preprocessing the code, you just put in some tags that the compiler can ignore.
What you are looking for are "annotations" - you basically want to annotate your code with some nice text that will not affect the compiler.
This basically requires defining some specialized Java types for this using the #interface keyword and then you can use them to write things like:
public void doStuff(#Input invar, #Output outvar) {
...
These annotations can be simply:
#interface Input {}
#interface Output {}
or you can add more features and even use reflection to examine them in runtime.
See the linked documentation above for more details.

Related

Sharing defines or enums between C++ and Java

Starting to digg into java, coming from c++. I am calling some functions in java from c++ (qt / Android). I miss a way to predefine some tags shareable between both languages avoiding having to define them twice or using strings.
Something like
define OPERATION_START 0X01
in c that would be compilable/readable in java.
Does something like this exists or you know some trick to achieve it?
Edit: How about something like this:
A java file stuff.java with
public enum Stuff{
Table, Apple, Beach, Eye };
and in Cpp+
'#define public
'#include "stuff.java"
'#undef public
Would that work? java would enumerate from 0 as does c, right?
You need something that can read one of the definitions and export the other.
There are a bunch of things that can do this.
Two that I know of are:
SWIG and protocol buffers.
SWIG will read the C++ declarations and generate code with the same things in other languages.
Protocol buffers will read some proprietary declaration and generate code for all the languages you need.
There are probably others as well, and I don't know of anything that is lighter weight than those. BTW, those are also good for defining more complex structures that you want to pass between C++ and java (and other languages).
You could model the shared definitions/enumerations in UML or maybe a DSL and use code generation from there to create matching definitions in Java and C++.
Or you could probably also define them in Java classes and build a generator which uses reflection to generate matching C++ headers from that.

placeholder for any code

I need to define a object at runtime like below.
Filter rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL,
new RegexStringComparator(".*-.5"));
I am reading one String which is having code like below
String _filterString = "RowFilter(CompareFilter.CompareOp.EQUAL,
new RegexStringComparator(\".*-.5\"))";
Now I need to define a filter object by using the above String.
I know, this type of problems we can achieve by using Reflections.But I am looking for alternatives. Is there any simple way to solve problems like this?
The Java Scripting API allows embedding of miscellaneous languages like JavaScript and have bindings to Java variables and methods. In your case the language BeanShell (Java subset) can be used.
Java Compiler can be used for compiling at Runtime, but it requires a full source (Compilation Unit). I don't think a single expression can be compiled. Maybe, you can work out from here to get your objects from the classes compiled at runtime.

Programatic code modification (e.g. variable extraction) in Java

I know it's possible to do nice stuff with Reflection, such as invoking methods, or altering the values of fields. Is it possible to do heavier code modification, though, at runtime and programmatically?
For instance, if I have a method:
public void foo(){
this.bar = 100;
}
Can I write a program that modifies the innards of this method, notices that it assigns a constant to a field, and turns it into the following:
public int baz = 100;
public void foo(){
this.bar = baz;
}
Perhaps Java isn't really the language to do this kind of thing in - if not, I'm open to suggestions for languages that would allow me to basically reparse or inspect code in this way, and be able to alter it so precisely. I might be pipe dreaming here though, so please tell me if this is the case also.
Just adding a suggestion from a friend - Apache Commons' BCEL looks excellent:
http://commons.apache.org/bcel/manual.html
The Byte Code Engineering Library (Apache Commons BCEL™) is intended to
give users a convenient way to analyze, create, and manipulate (binary)
Java class files (those ending with .class). Classes are represented by
objects which contain all the symbolic information of the given class:
methods, fields and byte code instructions, in particular.
Such objects can be read from an existing file, be transformed by a
program (e.g. a class loader at run-time) and written to a file again.
An even more interesting application is the creation of classes from
scratch at run-time. The Byte Code Engineering Library (BCEL) may be
also useful if you want to learn about the Java Virtual Machine (JVM)
and the format of Java .class files.
You are looking for software that allows you to do bytecode manipulation, there are several frameworks to achieve this, but the two most known currently are:
ASM
javassist
When performing bytecode modifications at runtime in Java classes keep in mind the following:
If you change a class's bytecode after a class has been loaded by a classloader, you'll have to find a way to reload it's class definition (either through classloading tricks, or using hotswap functionalities)
If you change the classes interface (example add new methods or fields) you will be able only to reach them through reflection.
It's probably fair to say that Java wasn't designed with this purpose in mind, but you can do it potentially. How and when depends a little on the ultimate aim of the exercise. A couple of options:
At the source code level, you can use the Java Compiler API to
compile arbitrary code into a class file (which you can then load).
At the bytecode level, you can write an agent that installs a
ClassFileTransformer to arbitrarily alter a class "on the fly"
as it is loaded. In practice, if you do this, you will also probably
make use of a library such as BCEL (Bytecode Engineering
Library) to make manipulating the class easier.
You want to investigate program transformation systems (PTS), which provide general facilities for parsing and transforming languages at the source level. PTS provide rewrite rules that say in effect, "if you see this pattern, replace it by that pattern" using the surface syntax of the target language. This is done using full parsers so the rewrite rule really operates on language syntax and not text; such rewrite rules obviously won't attempt to modify code-like text in comments, unlike tools based on regexps.
Our DMS Software Reengineering Toolkit is one of these. It provides not only the usual parsing, AST building and prettyprinting (reproducing compilable source code complete with comments), but also supports symbol tables and control and data flow analysis. These are needed for almost any interesting transformations. DMS also has front ends for a variety of dialects of Java as well as many other languages.
Bytecode transformers exist because they are much easier to build; it is pretty easy to "parse" bytecode. Of course, you can't make permanent source changes with a bytecode transformer, so it is lot less useful.
You mean like this?
String script1 = "println(\"OK!\");";
eval( script1 );
script1 += "println(\"... well, maybe NOT OK after all\");";
eval( script2 );
Output:
OK!
OK!
... well, maybe NOT OK after all
... use a scripting extension to Java. Groovy and other things like that would probably allow you to do what you want. I've written a scripting extension which integrates with Java through reflection almost seamlessly myself; contact me if you're interested in the details.

Using Dot Operator(JSTL) in Java

I have a requirement where I need to traverse a hierarchy of Java beans and the hierarchy is different based on the starting point. What would be ideal is if I would be able to use the "dot operator" from JSTL in my Java class.
Then I can have a static map of Strings to describe my hierarchy..something like:
clazz1=attribute1.attribute2
clazz2=attribute3.attribute4
I look up which class and which attributes I need to drill down and go to the root object.
I am coding for it anyway, just checking if BeanUtils etc had such a facility already since seems to me like it can be an useful feature.
You could write some of your code in groovy - it compiles to java bytecode so interoperates perfectly.

How to mark java code such that it's not compiled [duplicate]

This question already has answers here:
Java conditional compilation: how to prevent code chunks from being compiled?
(9 answers)
Closed 9 years ago.
I'm wondering if there if a Java equivalent for C's
#if 0
... Some Code ...
#endif
Which can be used around code blocks we don't want to compile. Adding block quotes:
/*
... Some Code ...
*/
also has the same effect, but the problem is, we have to ensure there are no single line comments
// some comment
in the block.
static final fields can be use for conditional compilation.
static final boolean DEBUG = false;
if (DEBUG) {
some code ....
}
some code will be removed by the compiler.
It is also possible to use the assert keyword to enable and disable some part of the code. Use java -ea: .. to control if the code should be enabled or disable. See http://docs.oracle.com/javase/1.5.0/docs/guide/language/assert.html
There are no pre-processor directives in Java. Your best choice is commenting out code.
There are several solutions:
Use a preprocessor - I think that it will work with the standard CPP. There were some Java specific proprocessors as jappo and java+ that you can try
Replace the #if 0 with a true if:
if(false) {
code
}
The condition can be refined by querying the system properties:
if(System.getProperty("NO_COMPILE").equals("true")) {
code
}
This has the advantage that it can be easily set either from ANT or from Eclipse.
EDIT: Please remark that with if the code will actually be compiled and present in the .class files. Moreover, although querying system properties is more elegant, is done at runtime not at compile time hence is not quite inline with original requirement. The if(false) is on a 2nd tought better.
EDIT2: an even better solution I have just found: http://prebop.sourceforge.net/
I can't even begin to imagine why this is an issue (as described) but I suspect the easiest thing to do is to grep for // in the code before you compile it (or commit it to your versioning repo). I don't think there's anything in eclipse (if that's what you're using) to help you and I'm almost positive that java has no built in mechanism like the one you're describing in C.
I saw this somewhere a while ago:
// /*
class SomeClass{
int withSomeField;
..............
}
// */
And you can put the //s in and and remove them as necessary. It's probably multiline comments that would cause problem if they were in there, though.
if(false) works well for me (using Eclipse).
you can just use Java Preprocessor and I guess it will be better way than flags
http://code.google.com/p/java-comment-preprocessor/
flags of course allow to cut and to add blocks on the compilation phase but preprocessor allows to make the process much more flexible
Instead of trying to make the code conditional by preprocessing the source-code (as C does), use object oriented programming: use design patterns such as Strategy, and dependency injection, to make code conditional.
There's not a Java-equivalent of the preprocessor's directive used in C/C++ languages.
Anyhow, you could do something similar using annotations or ANT, as briefly explained here
Using annotations to add C like preprocessor directives
or here
How to do Conditional Compilation with Java

Categories