/**
* @author lautturi.com
* Java example: Get instance object by String at runtime in java
*/
import java.util.*;
import java.lang.reflect.Method;
class Person{
public String pname = "hello;java world!";
int age;
public Person() {
}
public Person(String string, int i) {
pname = string;
age = i;
}
public String getName() {
return pname;
}
public void mySplit() {
try {
Object instance = getClass().getDeclaredField("pname").get(this);
Method m = instance.getClass().getMethod("split", String.class);
Object returnValue = m.invoke(instance, ";");
if(returnValue instanceof String[])
{
for(String s : (String[])returnValue )
{
System.out.println(s);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Lautturi {
public static void main(String[] args) {
new Person().mySplit();
}
}
output:
hello java world!