I’ve been thinking for years (as I’m sure many programmers do): “If I designed a language, what would it be like”. As time goes on, I’ve come up with many ideas, but I find it interesting that several aspects have stayed the same:
- C/C++/Java style syntax
- Light weight
- VM driven
- Possibly even Java byte codes
- Network friendly (move objects round a’la RMI / Serialization)
Last night I was thinking about it again, and particularly about Java annotations. I know many who hate annotation because they have been baddly abused already. I personally love them, but not everywhere, and not for everything. My main problem with annotations is that the actual meta-data, and the code that drives them are completely separate. What I want are: compile time annotations. Something more like:
@Target(ElementType.METHOD) public @class CachedResult { public void run(Node target) { if(target instanceof MethodNode) { MethodNode method = (MethodNode)target; if(method.getParameterTypes().length > 0) { throw new IllegalArgumentException("Bla!!!"); } ClassNode clazz = method.getDeclaringClass(); String name = method.getName(); String fieldName = generateFieldName(name); FieldNode node = clazz.createField(method.getReturnType(), fieldName); method.setName("_cached_" + name); method.setAccess(AccessModifiers.PRIVATE); MethodNode cacher = clazz.createMethod(method.getReturnType(), name); StringBuilder code = new StringBuilder(); code.append("if(").append(fieldName).append(" == null) {"); code.append(fieldName).append(" = _cached_").append(name).append("();"); code.append("}"); code.append("return ").append(fieldName).append(";"); cacher.eval(code.toString()); } else { throw new IllegalArgumentException("Bla!!!"); } } ... }
The above “annotation” would cause the compiler to rename the annotated method to “_cached_<methodname>”. The method would be invoked once and the result would be put in a field, which would be returned from then on. It’s a simple enough trick which would make life just that little bit easier. It’s also not terribly complex to put in a compiler. It’s simply a DOM style API for accessing the classes, fields and methods, and then being able to “eval” code into a method (also not challenging). The result: you can add new tricks to the compiler really easily.
June 18, 2012 at 4:45 pm
thats can be done with AOP too, like dis – http://scribblejava.wordpress.com/2011/09/28/java-custom-annotation-with-aop-spring/
October 2, 2017 at 11:33 pm
The Xtend language’s Active Annotations would allow you to do this, see https://www.eclipse.org/xtend/documentation/204_activeannotations.html