查看类中是否存在字段 [英] See if field exists in class

查看:86
本文介绍了查看类中是否存在字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含各种变量的类

I have a class with various variables

public class myClass{

    public int id;
    public String category;
    public String description;
    public String start;
    public String end;
}

有没有办法通过创建内部函数或检查来检查调用对象,无论变量是否存在?

Is there a way to check, either by creating an internal function or checking from the calling object, whether or not a variable exists?

例如检查myClass是否包含一个名为category的变量(确实如此)。或者它是否包含一个名为foo的类别(它没有)。

E.g. To check whether myClass contains a variable called "category" (it does). Or whether it contains a category called "foo" (it does not).

推荐答案

你的编译器通常很清楚,并且运行时允许您使用反射检查加载的类。

Your compiler usually knows that pretty well, and the runtime lets you examine loaded classes with reflection.

Object someObject = ...
Class<?> someClass = someObject.getClass();
Field someField = someClass.getField("foo");

getField() 方法将抛出一个如果无法找到该字段,则会出现异常。

The getField() method will throw an exception if the field can not be found.

这篇关于查看类中是否存在字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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