【问题标题】:Get an attribute's class from its name从属性的名称中获取属性的类
【发布时间】:2012-01-08 19:21:43
【问题描述】:

样品不工作:

Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();

Field f = c.getDeclaredField("myColor");
f.setAccessible(true);

String valueOfMyColor = (String) f.get(o);

此代码中的问题是您必须使用 String 类进行强制转换。我正在寻找的是能够从其名称中找到属性的类。

例如:

class Brush {
    Color myColor;
}

//Somewhere else, in a far far away galaxy
Class<?> c = getMyClassFromAttributeName("myColor");
// and c should be of type Color

我试过了

Field f = this.getClass().getDeclaredField(code);
Class<?> c1 = f.getClass(); //Gives Field 
Class<?> c2 = f.getDeclaringClass(); //Gives Brush

谢谢!

PS: 使用来自In Java, how to get attribute given the string with its name?的示例代码

【问题讨论】:

    标签: java class reflection dynamic attributes


    【解决方案1】:

    尝试:

     field.getType();
    

    这对我有用 (现在写了 100 遍:“在问一些琐碎的问题之前,我总是会阅读 javadoc 并查找公共接口”)。

    【讨论】:

    • 现在你必须这样做 100 次:“我会总是检查我的拼写之前在 StackOverflow 上发布我的帖子,尤其是在发表评论之前会咬我$$"。
    【解决方案2】:

    使用Field.getType();

    例子:

    Class<?> fieldType = f.getType(); //Should return Color.
    

    【讨论】:

    • 那么你怎么能在当前对象中修改它呢?
    • @Camille R,我不关注,请详细说明。
    • 我正在寻找一种能够从“抽象”字段修改字段的方法。我终于找到了 ((Color)f.get(this)).setValue(value);正在工作:)
    【解决方案3】:

    使用Field.getType()

    Field f = Brush.class.getDeclaredField("myColor");
    Class<?> c = f.getType();
    

    不过,您将无法使用它从代码中删除强制转换。

    【讨论】:

    • 呵呵,我们已经过了 Java 1.4 时代(提示:泛型)。
    猜你喜欢
    • 2021-12-04
    • 2018-11-16
    • 2014-06-27
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2013-06-07
    相关资源
    最近更新 更多