
Class<> clazz = refgetClass();
Method method=clazzgetMethod("getLength");
Systemoutprintln(methodinvoke(ref));
Class c = null;
try {
c = ClassforName("comibmlantestSub");
} catch (ClassNotFoundException e) {
eprintStackTrace();
}
Class superClass = cgetSuperclass();
Field[] fields = superClassgetDeclaredFields();
这是得到父类的属性
for(int i=0;i<fields length;i++)
{
fields [i]setAccessible(true);
Systemoutprintln(fields [i]getType());
fields [i]set();
}
你可以这么写:
class BodyImpl implements Body{
//do something
public static void main(String[] args) {
Type[] interfaces = BodyImplclassgetInterfaces();
ParameterizedType firstInterface = (ParameterizedType) interfaces[0];
Class c = (Class) firstInterfacegetActualTypeArguments()[0];
Systemoutprintln(cgetName()); // prints "AtomEntry"
}
}
就得到你所要的接口参数了!
答案是没法获取。
首先反射获取的是类、属性、或者方法的定义,就拿方法来说,方法的定义是什么呢?
方法的定义包括:方法名,方法的参数类型列表,方法的返回值类型。
方法的参数类型列表包括什么呢?
包括每个参数的顺序和参数类型。
参数值是什么?是在这个方法被调用的时候传入的参数叫做参数值。反射呢,是获取的它的定义,并不牵扯调用,所以说没法获取。
把这个方法写在基类
public void getFields() {Class<> cls = getClass();
for (; cls != Objectclass; cls = clsgetSuperclass()) {
Field[] fs = clsgetDeclaredFields();
for (Field f : fs) {
Systemoutprintln(fgetName());
}
}
}
下例演示了通过反射获取 Test 类对象 t 的 iVal, strVal 成员变量的值:
import javalangreflectField;class Test {
private int iVal;
private String strVal;
public Test(int iVal, String strVal) {
thisiVal = iVal;
thisstrVal = strVal;
}
}
public class App {
public static void main(String[] args) {
// 创建一个 Test 对象
Test t = new Test(123, "Hello");
// 获取对象 t 的 Class
Class<> tt = tgetClass();
try {
// 获取 Test 类的 iVal 字段 Field
Field field = ttgetDeclaredField("iVal");
// 设置可访问
fieldsetAccessible(true);
// 获取 iVal 的值
int val = fieldgetInt(t);
Systemoutprintln(val);
Field strValField = ttgetDeclaredField("strVal");
strValFieldsetAccessible(true);
String strVal = (String)strValFieldget(t);
Systemoutprintln(strVal);
} catch (NoSuchFieldException | SecurityException e) {
eprintStackTrace();
} catch (IllegalArgumentException e) {
eprintStackTrace();
} catch (IllegalAccessException e) {
eprintStackTrace();
}
}
}
JavalangClass
getDeclaredFields()
返回 Field 对象的一个数组,这些对象反映此 Class
对象所表示的类或接口所声明的所有字段。
JavalangreflectField
getName()
返回此 Field 对象表示的字段的名称。
getGenericType()
返回一个 Type 对象,它表示此 Field 对象所表示字段的声明类型。
以上是jdk里面的一些用法,就是用你想要获取对象的属性得到它的class 然后调用 getDeclaredFields()就可以得到字段数组了。
然后再用下面的方法就可以得到属性名,类型这一些。
很简单,要想实现现复杂的功能就再找一下api 找出相应的方法。
以上就是关于java怎么通过反射获得所有的属性的值全部的内容,包括:java怎么通过反射获得所有的属性的值、怎样用java反射机制获得父类private 属性的值、如何利用java反射,获取属性接口的具体类等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)