首页 > 解决方案 > interfacename.class 返回什么?

问题描述

    ClassPathXmlApplicationContext context = new  ClassPathXmlApplicationContext ("applicationContext.xml");
    //retrieve bean from the spring container
    Coach theCoach = context.getBean("myCoach",Coach.class);
    //call methods on the bean
    System.out.println(theCoach.getDailyWorkout());
    System.out.println(theCoach.getDailyFortune());
    System.out.println(theCoach.getEmailAddress());
    System.out.println(theCoach.getTeam());
    //close the context
    context.close();

在上面的代码中,Coach.class 返回了什么

教练是一个界面。

标签: java

解决方案


Coach.class返回描述 Coach 接口结构的Class对象的实例。

假设我们有这个例子:

public interface Coach {
    int getName();
}

如果您将执行这些行:

Class<Coach> coachClass = Coach.class;
System.out.println(coachClass.getName());
for(Method m:coachClass.getMethods()) {
    System.out.println(m.getName());
}

您将获得接口的全名和声明的方法的名称。

简而言之Coach.class,返回界面的元数据。如果您想了解有关此主题的更多信息,那么我建议您阅读Java 反射

在您的情况下,这行代码:

Coach theCoach = context.getBean("myCoach",Coach.class);

返回实现 Coach 接口的对象的实例。您必须传递Coach接口的元数据,以便 Spring 知道您要查找的数据类型。


推荐阅读