使用反射访问静态最终变量 [英] Access static final variable using reflection

查看:99
本文介绍了使用反射访问静态最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有静态变量的Java类

I have a Java class with a static variable

package com.mytest
public class MyClass{
    public static final TextClass TEXT_CLASS = new TextClass();
}

如何访问对象 TEXT_CLASS 使用反射?

How can I access the object TEXT_CLASS using reflection?

(我有字符串com.mytest.MyClass.TEXT_CLASS。我需要访问该对象。)

(I have the string "com.mytest.MyClass.TEXT_CLASS". I need to access the object.)

推荐答案

访问静态字段的方式与普通字段完全相同,只有你不要需要将任何参数传递给 Field.get()方法(可以传递null)。

Accessing static fields is done exactly the same way as normal fields, only you don't need to pass any argument to Field.get() method (you can pass a null).

尝试这个:

Object getFieldValue(String path) throws Exception {
    int lastDot = path.lastIndexOf(".");
    String className = path.substring(0, lastDot);
    String fieldName = path.substring(lastDot + 1);
    Class myClass = Class.forName(className);
    Field myField = myClass.getDeclaredField(fieldName);
    return myField.get(null);
}

这篇关于使用反射访问静态最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆