Last active
February 20, 2018 07:24
-
-
Save westdabestdb/f42cd1fde25bb95db871c893ece30d9b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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