能不能把object转回interface

alphax 2007-07-11 02:07:13
我发现interface能够直接赋给object:
假设i1是一个interface:IAmNewer

Object o1 = i1; //可以通过编译

但是,能不能从o1得出一个IAmNewer接口呢?怎么做?
...全文
293 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
alphax 2007-07-12
  • 打赏
  • 举报
回复
thanks,昨晚通过几个小程序的练习,对object/interface终于有了进一步的认识了
hongqi162 2007-07-11
  • 打赏
  • 举报
回复
o1.getClass().getSuperclass()
alphax 2007-07-11
  • 打赏
  • 举报
回复
我只看到一个出错信息,以为就后面那个不能通过编译,回去再研究一下,明天再聊,谢谢!
sureyor 2007-07-11
  • 打赏
  • 举报
回复
汗,楼主getClass().getInterfaces[0].getName()能编译通过??
都不可能编译通过
正确的代码是:
System.out.println("interface name is: " + o.getClass().getInterfaces()[0].getName());

System.out.println("interface name is: " + i2.getClass().getInterfaces()[0].getName());
alphax 2007-07-11
  • 打赏
  • 举报
回复
有点糊涂,初步理解是任何interface都属于Object?

然后下面的代码中的Test1.java的最后一句不通过? Why?

//main\IAmNewer.java
package main;

public interface IAmNewer {
String getName();
}


//main\IAmNewerImpl.java
package main;



public class IAmNewerImpl implements IAmNewer {
private String name = "hello";

public IAmNewerImpl () {
super();
}

public String getName()
{
return name;
}
}


//main\Test1.java
package main;

import main.*;

public class Test1 {
public static void main(String[] args)
{
IAmNewer i = new IAmNewerImpl();
Object o = i;
if (o.getClass().isInstance(i))
System.out.println("yes, o is a IAmNewer.");

String name = o.getClass().getSuperclass().getName();
System.out.println("class name is: " + name);
System.out.println("interface name is: " + o.getClass().getInterfaces[0].getName()); //OK

IAmNewer i2 = (IAmNewer) o;
System.out.println("the name is: " + i2.getName());
System.out.println("class name is: " + i2.getClass().getName());
System.out.println("interface name is: " + i2.getClass().getInterfaces[0].getName()); //failured???
/*
compiler error: symbol not found "getInterfaces"
*/
}
}


为什么前面的getClass().getInterfaces[0].getName()可以通过编译而后面的不行?这说明interface又不完全是object?

迷惑
alphax 2007-07-11
  • 打赏
  • 举报
回复
谢谢!:)

我先试试,广告时间后回来
sureyor 2007-07-11
  • 打赏
  • 举报
回复
o1.getClass().getSuperclass()
获取基类
sureyor 2007-07-11
  • 打赏
  • 举报
回复
o1.getClass().getInterfaces()

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧