Skip to content

Instantly share code, notes, and snippets.

@westdabestdb
Last active February 20, 2018 07:24
Show Gist options
  • Save westdabestdb/f42cd1fde25bb95db871c893ece30d9b to your computer and use it in GitHub Desktop.
Save westdabestdb/f42cd1fde25bb95db871c893ece30d9b to your computer and use it in GitHub Desktop.
public class Manipulator {
public Manipulator(Class m){
manipulate(m);
}
private void manipulate(Class m){
PrintStream myStream = new PrintStream(System.out){
@Override
public void println(String mystr) {
String[] str = mystr.split("\\s+");
mystr = "";
//here I override the default println method, split user's printable string into array of words then I set that string empty.
String match = ""; //this will hold each match
for(String s : str) {
if(s.charAt(0) == '$' && s.charAt(1) == '{' && s.charAt(s.length()-1) == '}') {
//here i search for ${object name} and I replace them with empty character.
match = s;
match = match.replace("$", "");
match = match.replace("{", "");
match = match.replace("}", "");
if(match.length() > 0) {
try {
match = returnVal(match, m);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
mystr += match + " ";
} else {
mystr += s + " ";
}
} else {
mystr += s + " ";
}
}
super.println(mystr);
}
};
System.setOut(myStream);
}
private String returnVal(String s, Class operator) {
Field[] fields = operator.getDeclaredFields();
//here I reach the objects I've created in the class that I passed to my Manipulator.class
Class<?> _class = Class.forName(operator.getName());
Constructor<?> _constructor = _class.getDeclaredConstructor();
Object _instanceObj = _constructor.newInstance();
//I need instance from the class I've passed, so I recreated the class in my method and pointed to it's instance.
for (int i = 0; i < fields.length; i++){
Field f = fields[i];
f.setAccessible(true);
//since fields can be private, I make them accessible to this method.
Object value = f.get(_instanceObj);
if(s.equals(f.getName())){
s = value.toString();
//if user's string matches the name of object, I replace this string with value of the object.
}
}
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment