如何确定字段在哪个类中声明

发布于 2024-12-13 22:13:06 字数 465 浏览 1 评论 0原文

有没有办法确定在哪个类中从这样的代码声明字段:

Class myObjClass = myObj.myField.getWhereDeclaredClass ();

编辑: 也许我没有正确表达自己。 考虑 myObj 类如下:

class MyObj {
  MySecondObj myField = new MySecondObj ();
}

myField 不是 java.lang.reflect.Field 类型,并且我不想将硬编码字符串 literlas 与 getField (String) 一起使用。语法必须是:

myObj.myField.getWhereDeclaredClass ()

有办法做到这一点吗?

Is there a way to determine in which class a field is declared from such code:

Class myObjClass = myObj.myField.getWhereDeclaredClass ();

Edit:
Maybe i didn't express my self properly.
Consider myObj class as following:

class MyObj {
  MySecondObj myField = new MySecondObj ();
}

myField IS NOT of type java.lang.reflect.Field, and i don't want to use hard coded string literlas with getField (String). The syntax must be:

myObj.myField.getWhereDeclaredClass ()

is there a way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹泡泡o 2024-12-20 22:13:06

字段。 getDeclaringClass() 可能有效。

示例:

class A{
    public int f;
}
class B extends A{
    public int g;
}
class C extends B{
    public int h;
}

class Test{

    public static void main(String[]args) throws Exception{

        Class<C> c = C.class;
        System.out.println(c.getField("f").getDeclaringClass());
        System.out.println(c.getField("g").getDeclaringClass());
        System.out.println(c.getField("h").getDeclaringClass());

    }

}

打印:

class A
class B
class C

编辑:

我个人不知道有什么方法可以在不反思的情况下做到这一点。再说一遍,编写“.myField”意味着您知道该对象具有该字段,因此从某种意义上说它仍然是硬编码的,并且它还意味着您的反射代码实际上基本上没有机会抛出异常。

有什么特殊原因不使用反射吗?如果是性能,您可以通过反射执行一次,然后对获得的值进行硬编码。

Field.getDeclaringClass() might work.

Example:

class A{
    public int f;
}
class B extends A{
    public int g;
}
class C extends B{
    public int h;
}

class Test{

    public static void main(String[]args) throws Exception{

        Class<C> c = C.class;
        System.out.println(c.getField("f").getDeclaringClass());
        System.out.println(c.getField("g").getDeclaringClass());
        System.out.println(c.getField("h").getDeclaringClass());

    }

}

Prints:

class A
class B
class C

Edit:

I personally don't know of any way to do it without reflection. Then again, to be writing ".myField" implies that you know the object to have that field, so in a sense it's still hardcoded, and it also implies that there's basically no chance of your reflective code actually throwing an Exception.

Is there any particular reason not to be using reflection? If it's performance, you could do it once with reflection and then hardcode the value you got.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文