Created
April 9, 2013 23:39
-
-
Save pvorb/5350384 to your computer and use it in GitHub Desktop.
Accessible object literals in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Global { | |
public static Undefined undefined = Undefined.getInstance(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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