1

这是我的方法

public AuctionItem[] getOpenAuctions() throws RemoteException {

    return itemList.toArray((AuctionItem[]) java.lang.reflect.Array
            .newInstance(itemList.getClass(), itemList.size()));

}

这是我的错误

Exception in thread "main" java.lang.ClassCastException: [Ljava.util.LinkedList; cannot be cast to [LAuction.AuctionItem;
at Auction.AuctionImpl.getOpenAuctions(AuctionImpl.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source)
at $Proxy0.getOpenAuctions(Unknown Source)
at Seller.SellerMain.main(SellerMain.java:38)

它出什么问题了?

4

2 回答 2

6

尝试:

return itemList.toArray(new AuctionItem[itemList.size()]);

您编写的代码的问题是itemList.getClass()返回 class LinkedList。因此,该Array.newInstance()方法正在创建一个LinkedList[],然后您尝试将其类型转换为AuctionItem[]. 由于这两种类型的赋值不兼容,所以它抛出一个ClassCastException.

于 2012-05-11T18:04:47.800 回答
1

itemList.getClass()返回LinkedList.class,因为它是一个 LinkedList。 itemList.peek().getClass()会解决这个问题,但前提是列表至少有一个元素。

为什么不只是:

public AuctionItem[] getOpenAuctions() {
    return itemList.toArray(new AuctionItem[itemList.size()]);
}
于 2012-05-11T18:07:34.870 回答