Skip to content

Instantly share code, notes, and snippets.

@pvorb
Created April 9, 2013 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvorb/5350384 to your computer and use it in GitHub Desktop.
Save pvorb/5350384 to your computer and use it in GitHub Desktop.
Accessible object literals in Java
public class Global {
public static Undefined undefined = Undefined.getInstance();
}
import java.lang.reflect.*;
public class ObjectLiteral {
public Object apply(String key) {
Class cls = this.getClass();
try {
Field fld = cls.getField(key);
return fld.get(this);
} catch (Exception e) {
return Global.undefined;
}
}
@Override
public String toString() {
Class cls = this.getClass();
StringBuilder sb = new StringBuilder();
sb.append('{');
Field[] flds = cls.getDeclaredFields();
int length = flds.length;
int i = 0;
for (Field fld : flds) {
String key = fld.getName();
Object value = this.apply(key);
sb.append(key + ": ");
sb.append(value);
if (++i < length)
sb.append(", ");
else
sb.append('}');
}
return sb.toString();
}
}
public class ObjLiteralsTest {
public static void main(String[] args) {
ObjectLiteral user = new ObjectLiteral() {
public int id = 1;
public String name = "pvorb";
};
// will print "{id: 1, name: pvorb}"
System.out.println(user);
}
}
public class Undefined {
private static Undefined instance = null;
private Undefined() {
}
public static Undefined getInstance() {
if (instance == null)
instance = new Undefined();
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment