首页 > 试题广场 >

reflection是如何工作的

[单选题]
考虑下面这个简单的例子,让我们看看reflection是如何工作的。
import java.lang.reflect.*;
public class DumpMethods{
	public static void main(String[] args) {
		try {
			Class c=Class.forName(args[0]);
			Method m[]=c.getDeclaredMethods();
			for (int i = 0; i < m.length; i++) {
				System.out.println(m[i].toString());
			}
		} catch (Throwable e) {
			System.err.println(e);
		}
	}
}
其中"c.getDeclaredMethods"的作用是:
  • 取得类的公有方法对象
  • 取得类的所有公有方法名称
  • 取得类的所有方法对象
  • 以上选项都不正确
=====目测答案从C修改为D了,所以大家若碰到,就选D咯(lll¬ω¬)=====
public Method[] getDeclaredMethods()返回类或接口声明的所有方法,包括public, protected, default (package) 访问和private方法的Method对象,但不包括继承的方法。当然也包括它所实现接口的方法。
public Method[] getMethods()返回类的所有public方法,包括其继承类的公用方法,当然也包括它所实现接口的方法。
编辑于 2017-05-04 14:57:27 回复(23)
纠正,选D。做了两遍还是错的,自惭中......决定把Class类好好看一遍。
当一个类或接口被加载到JVM的时候便会产生一个与之关联的一个Java.lang.Class对象,我们可以通过此Class对象来得到被装入的类的详细信息。
其中:
Method[] getDeclaredMethods() 返回 Class 对象表示的类或接口的所有已声明的方法数组,但是不包括从父类继承和接口实现的方法。
Method[] getMethods() 返回当前 Class 对象表示的类或接口的所有公有成员方法对象数组,包括已声明的和从父类继承或实现接口的方法。

其他方法的介绍大家可以看此博客:http://utopialxw.iteye.com/blog/1220476
编辑于 2018-01-10 13:36:02 回复(5)

getDeclaredMethods ()
                    返回   Method   对象的一个数组,这些对象反映此   Class   对象表示的类或接口声明的所有方法, 包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。

 

发表于 2016-01-08 10:09:45 回复(1)
返回的是对象吧 在本题中作用是取得方法 所以 那就没错  选择C
Method[] getDeclaredMethods()
返回Method对象的一个数组,这些对象反映此Class对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
发表于 2015-10-22 14:50:18 回复(8)

public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法, 包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法

发表于 2015-11-05 21:52:58 回复(3)
看注释
---------------------------------------


发表于 2016-08-21 00:25:42 回复(1)
返回所有方法 与 返回所有方法对象总赶脚有点不一样
发表于 2015-10-20 00:48:56 回复(0)
getDeclaredMethods()方法返回类的所有方法,但不包括类继承来的方法。 因此选D
发表于 2018-08-01 18:53:57 回复(0)
确定屏蔽该题后,该试题将再也不会出现以后的组卷中。
发表于 2018-03-16 16:21:58 回复(0)

public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。

发表于 2017-08-13 20:13:58 回复(0)
我觉得D,应该是输出以及声明的方法对象,不包含Object方法
发表于 2016-04-06 19:01:01 回复(0)
<p>getDeclareMethod 获取该类的所有方法,不包括从父类继承来的;</p><p>getMethod 过去该类的所有public 方法,包括从父类继承来的;</p><p><br></p><p>另外得到的method []是方法数组,不是对象</p>
发表于 2020-07-31 09:25:26 回复(0)

比较疑惑,如果代码如下

class A{ 
public void test() {} 
} 
public class B extents A{
   public static void main(String []args){ 
      //B b = new B() 不影响输出结果
      A a = new B();
      Class c = a.getClass();
      Method [] m = c.getDeclaredMethods(); 
      for(Method x : m) { 
         System.out.println(x); 
      } 
   } 
}

输出的结果为:

public static void B.main(java.lang.String[]) 
public void B.test() 
  1. 如果把class B的public去掉或者把方法声明除了public之外的权限修饰符或者加上final或者static只有第一行输出
  2. 官方给的文档描述:

    Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package)access, and private methods, but excluding inherited methods

  3. 后面这个不包含继承的方法指的是什么? 而且如果是父类声明为public则输出也只有第一行
    这么看来指的是上述所说的情况,为什么会这样?跟官方的描述有点出入了 而且官方还描述了一些情况下结果,所以是否跟JVM有关,得查阅资料看看能否找到答案
编辑于 2019-11-04 01:45:38 回复(0)
当一个类或者接口被加载到JVM的时候便会产生一个与之关联的一个java.lang.Class对象,我们可以通过此Class对象来得到被装入的类的详细信息:
其中
public Method[] getDeclareMethods():返回Class对象表示的类和接口的所有已声明的方法数组,包括pubic,protected,default和private的方法对象,但是不包括从父类继承和接口实现的方法

public Methods[] getMethods(): 返回当前Class对象表示的类或接口的所有公有成员方法对象数组,包括已声明的和从父类继承或实现接口的方法
参考原文:https://blog.csdn.net/weixin_43224539/article/details/91353925 

发表于 2019-06-09 16:29:09 回复(0)
getDeclareMethods() 返回的是类或者接口的所有方法,但是不包含继承的方法;
getMethods()返回类所有public方法,包含继承类的公有方法

查看源码 getDeclareMethods() 返回类所有申明的方法
/**  *  * Returns an array containing {@code Method} objects reflecting all the  * declared methods of the class or interface represented by this {@code  * Class} object, including public, protected, default (package)  * access, and private methods, but excluding inherited methods. 
* */
@CallerSensitive public Method[] getDeclaredMethods() throws SecurityException {
    checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);  return copyMethods(privateGetDeclaredMethods(false)); }
getMethods() 返回所有pubblic的方法 包含实现的接口的方法和继承的方法
/**  * Returns an array containing {@code Method} objects reflecting all the  * public methods of the class or interface represented by this {@code  * Class} object, including those declared by the class or interface and  * those inherited from superclasses and superinterfaces.  */
@CallerSensitive public Method[] getMethods() throws SecurityException {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);  return copyMethods(privateGetPublicMethods()); }


编辑于 2019-01-29 10:18:56 回复(1)
A B 错。
getDeclaredMethods 取得不仅仅是 public的方法,default protected private都会给你取出来。 
C 错,严格说也可以说对。(不想玩文字中游戏)
取得类的所以方法对象,说的不全面,父类的它就取不出来,就比如Object类的 wait hashCode 等方法就没给你取出来,

我贴一些代码,你们跑一下方法就知道区别了:

interface interface001 {}
interface interface002 {}

class X implements interface001 ,interface002{
    public int x = 0;

    public X() {
    }

    public void helloX() {
        System.out.println("hello X ...");
    }
}

class Y extends X {
    public int y = 0;

    public void helloY() {
        System.out.println("hello Y ...");
    }
}

class BasePerson extends Y {
    private String name;
    private int age;

    private BasePerson(String name) {
    } // //private构造方法

    BasePerson(int age) {
    }

    ; //default 构造方法

    protected BasePerson(int age, String name) {
    } //protected构造方法

    public BasePerson() {
    }

    // java.lang.InstantiationException
    // 因为类中并没有存在无参构造方法,所以根本无法直接使用newInstance()方法进行实例化的。
    public BasePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // private方法
    private void privateMethod() {
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void hello() {
        System.out.println("hello person ...");
    }
}

下面是测试方法:

 @Test
    public void test_Method() {
        Class<?> clazz = null;
        try {
            clazz =  Class.forName("indi.sword.util.base.reflect.BasePerson"); // 传入完整的“包.类”名称实例化Class对象
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        /**
         * 注意:public methods.
         * getMethods()
         * Returns an array containing {@code Method} objects reflecting all the
         * public methods of the class or interface represented by this {@code
         * Class} object, including those declared by the class or interface and
         * those inherited from superclasses and superinterfaces.
         */
        Method[] method = clazz.getMethods(); //得到本类中的全部public方法,包括继承来的或者接口来的
        System.out.println("clazz.getMethods().length -> " + method.length);
        String methodsStr = Arrays.stream(method).map(methodArgs -> methodArgs.getName()).collect(Collectors.joining(",", "---", "---"));
        System.out.println("clazz.getMethods() -> " + methodsStr);

        System.out.println("---------------------------------");
        System.out.println("Object.class.getMethods().length -> " + Object.class.getMethods().length); // 拿出Object的方法
        Arrays.stream(Object.class.getMethods()).map(methodArgs -> methodArgs.getName()).forEach(name -> {
            System.out.print(name + ",");
        });

        System.out.println();
        System.out.println("---------------------------------");
        /**
         * 注意:excluding inherited methods
         * Returns an array containing {@code Method} objects reflecting all the
         * declared methods of the class or interface represented by this {@code
         * Class} object, including public, protected, default (package)
         * access, and private methods, but excluding inherited methods.
         */
        Method[] declaredMethods = clazz.getDeclaredMethods();//得到本类中的全部方法,public  private default protected都取出来,但是父类的不算
        System.out.println("clazz.getDeclaredMethods().length -> " + declaredMethods.length);
        String declaredMethodsStr = Arrays.stream(declaredMethods).map(methodArgs -> methodArgs.getName()).collect(Collectors.joining(",", "---", "---"));
        System.out.println("clazz.getDeclaredMethods() -> " + declaredMethodsStr);
    }

控制台输出:

clazz.getMethods().length -> 16
clazz.getMethods() -> ---toString,getName,setName,getAge,hello,setAge,helloY,helloX,wait,wait,wait,equals,hashCode,getClass,notify,notifyAll---
---------------------------------
Object.class.getMethods().length -> 9
wait,wait,wait,equals,toString,hashCode,getClass,notify,notifyAll,
---------------------------------
clazz.getDeclaredMethods().length -> 7
clazz.getDeclaredMethods() -> ---toString,getName,setName,getAge,hello,setAge,privateMethod---
发表于 2017-10-29 10:10:59 回复(4)
public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。 public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法, 包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。
发表于 2017-09-13 23:08:52 回复(0)
返回类或接口声明的所有方法,不包括继承的方法。C错误,因为不包括继承的方法。
发表于 2017-07-25 22:17:23 回复(0)
取得类的所有方法对象,但是不包括继承的方法对象!!!
发表于 2017-05-31 07:20:20 回复(0)
getDeclaredMethods   和  getMethods  区别就是Declared="声明"的意思,所以 getDeclaredMethods是返回所有的方法,而 getMethods就返回公共方法
发表于 2017-01-13 22:51:34 回复(0)