java 在接口上使用 .getclass()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7961834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using .getclass() on an interface
提问by Erik
This is probably a very easy question. Hey I'm a student and relatively new to java and I'm currently studying for a midterm that I have tomorrow. One of the practice questions I am stuck on is what happens when you have something like:
这可能是一个非常简单的问题。嘿,我是一名学生,对 Java 比较陌生,我目前正在学习明天的期中考试。我坚持的练习问题之一是当您遇到以下情况时会发生什么:
System.out.println(interface1.getClass().getName());
System.out.println(interface1.getClass().getName());
interface1
has been declared as interface1 = class1
. I'm pretty sure it would print "class1" and not "interface1" because interface1
is not a class right? but I'm not sure as the question also says that if it produces a compile time error then say so. Our professor is known for tricking us and more then once I get back a quiz and still been confused as to why I got a problem wrong.
interface1
已被声明为interface1 = class1
. 我很确定它会打印“class1”而不是“interface1”,因为interface1
它不是一个类,对吗?但我不确定,因为问题还说如果它产生编译时错误,那么就这么说。我们的教授以欺骗我们而闻名,而且当我回到测验时,我仍然对为什么我做错了问题感到困惑。
回答by G_H
It's not because it's an interface that you'd get class1
, but because getClass()
will resolve to the runtime class of the instance. Since you've created it as a class1
, that's the runtime type. Won't give you a compile-time error.
这不是因为它是您将获得的接口class1
,而是因为getClass()
它将解析为实例的运行时类。由于您已将其创建为class1
,这就是运行时类型。不会给你一个编译时错误。
Getting a Class
object for an interface is possible via reflection.
Class
可以通过反射获取接口的对象。
Alternatively you can access the class more directly through the class
keyword:
或者,您可以通过class
关键字更直接地访问该类:
String className = Runnable.class.getName();