A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 吴光新 黑马帝   /  2013-8-10 05:30  /  980 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Jiewin 于 2013-8-14 07:25 编辑

查看API的描述,getDeclaredFields方法可以返回此类所有已声明字段的Field对象数组,
这些对象映射此Class对象所表示的类或接口所声明的所有字段。但输出结果只有x、y,
那么接口Inter中的z是怎么获取的?
  1. import java.lang.reflect.Field;

  2. interface Inter{
  3.     public int z = 8;
  4. }
  5. class ClassPoint implements Inter{
  6.     public int x;
  7.     private int y;
  8.     public ClassPoint(int x, int y) {
  9.         this.x = x;
  10.         this.y = y;
  11.     }
  12. }
  13. public class Demo {
  14.     public static void main(String[] args) throws Exception {
  15.         ClassPoint cp = new ClassPoint(3,5);
  16.         for(Field field : cp.getClass().getDeclaredFields()){
  17.             System.out.println(field.getName());
  18.         }
  19.     }
  20. }
复制代码

2 个回复

倒序浏览
import java.lang.reflect.Field;

interface Inter
{
        public int z = 8;
}

class ClassPoint implements Inter
{
        public int x;
        private int y;

        public ClassPoint(int x, int y)
        {
                this.x = x;
                this.y = y;
        }
}

public class Mamin
{
        public static void main(String[] args) throws Exception
        {
                ClassPoint cp = new ClassPoint(3, 5);
                for (Class<?> ca : cp.getClass().getInterfaces())// 先得到接口的Class对象数组
                {
                        ca.getFields();// 得到Field对象数组
                        for (Field fd : ca.getFields())// 遍历数组得到所有对象的名字
                        {
                                System.out.println(fd.getName());
                        }

                }
        }
回复 使用道具 举报
亲,如问题已解决请将分类的未解决改为已解决。

以后的问题贴也要及时更改分类哦~


保持队形,谢谢合作
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马