java—反射
反射机制调用方法:
1、获取对象,直接通过对象调用方法
2、第二种方法,通过方法名获取方法,执行方法
反射demo实体
package com.example.demo.reflection.bean;
/**
* @ Author :lzy
* @ Date :Created in 2019/8/14 15:59
* @ Description:
*/
public class TestBean {
public String string;
public String getString(String str){
return str+str;
}
public String getStr2(String str){
return str+str;
}
}
反射
package com.example.demo.reflection;
import com.example.demo.reflection.bean.TestBean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
package com.example.demo.reflection;
import com.example.demo.reflection.bean.TestBean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @ Author :lzy
* @ Date :Created in 2019/8/14 15:59
* @ Description:
*/
public class TestDemo {
public static void main(String[] args) {
//获取属性值
Class cls= TestBean.class;
Field[] declaredFields = cls.getDeclaredFields();
for (Field fiels:declaredFields
) {
System.out.println("获取对象属性"+fiels.getName());
}
TestBean testBean = new TestBean();
Class cls1 = null;
try {
cls1=Class.forName("com.example.demo.reflection.bean.TestBean");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method method=null;
try {
method=cls1.getMethod("getString",String.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Object invoke=null;
try {
//获取方法调用
invoke= method.invoke(testBean, "123");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println("反射方法获取:"+invoke);
TestBean testBean1=null;
try {
testBean1 = (TestBean) cls1.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
String string = testBean1.getString("123");
System.out.println("反射实体类获取:"+string);
}
}