//Get class name from object
public void getClassNameFromObject(){
Foo f = new Foo();
try {
Log.d(TAG, f.getClass().getName());
} catch ( Exception e){
Log.d(TAG, ""+e);
}
}
--09 16:48:30.784 12379 12379 D hello : com.test.simpletest.Foo
//Invoke method on unknown object
public void invokeMethod(){
Foo f = new Foo();
Method m;
try {
m= f.getClass().getMethod("printFoo",new Class[0]);
m.invoke(f);
} catch ( Exception e){
Log.d(TAG, ""+e);
}
}
07-09 16:48:30.784 12379 12379 D hello : Foo!
//Create object from Class instance
public void createObjectFromClassInstance(){
Class c = null;
Foo f = null;
//create instance of Class
try {
c = Class.forName("com.test.simpletest.Foo");
} catch ( Exception e){
Log.d(TAG, ""+e);
}
//Create instance of Foo
try {
f = (Foo) c.newInstance();
} catch ( Exception e){
Log.d(TAG, ""+e);
}
f.printFoo();
}
07-09 16:53:33.591 12766 12766 D hello : Foo!
//Get constructor and create instance
public void getConstructorAndCreateInstance(){
Class c = null;
//create instance of Class
try {
c = Class.forName("com.test.simpletest.Foo");
} catch ( Exception e){
Log.d(TAG, ""+e);
}
//Create instance of Foo
Foo f1 = null;
Foo f2 = null;
Constructor cons[] = c.getConstructors();
//get all constructors
try {
f1 = (Foo) cons[0].newInstance();
f2 = (Foo) cons[1].newInstance("Foo!");
} catch ( Exception e){
Log.d(TAG, ""+e);
}
f1.printS();
f2.printS();
}
07-09 17:19:04.317 14200 14200 D hello : null 07-09 17:19:04.317 14200 14200 D hello : Foo!
출처 : https://www.javacodegeeks.com/2013/09/java-reflection-tutorial.html
'java' 카테고리의 다른 글
| 반복문에서 label의 사용 (0) | 2019.09.12 |
|---|---|
| hashcode 및 equals를 같이 override 하는 이유 (0) | 2018.09.06 |
| Cloneable interface (LINK) (0) | 2018.07.18 |
| 접근 지정자 (0) | 2018.07.18 |
| install openjdk-8-jdk on unbuntu (0) | 2018.06.22 |