java - Eclipse SWT - 如何从 'id' 转换为可用类型

标签 java objective-c ios serialization

我正在尝试为以前仅支持基于 iPhone 的客户端的客户端/服务器应用程序创建 Android 客户端。该服务器的设计目的并不是支持其他设备,我需要能够处理的一些数据存储为通过使用 NSKeyedArchiver 序列化一个字节而生成的字节 block 。 iPhone 客户端上的 NSDictionary

为了处理反序列化,我尝试使用 Eclipse SWT,其中包括用于 Cocoa API 调用和类的 Java 绑定(bind),包括 NSKeyedArchiverNSKeyedUnarchiver。这些似乎有效,但是 NSKeyedUnarchiver.unarchiveObjectWithData() 返回一个 id 类型,并且我无法弄清楚如何将其转换为可用的东西(它实际上应该是一个NSDictionary)。显然,在 Objective-C 中,一个简单的转换就可以解决问题,但在 Java 中尝试同样的操作会在运行时抛出 ClassCastException :

Exception in thread "main" java.lang.ClassCastException: org.eclipse.swt.internal.cocoa.id cannot be cast to org.eclipse.swt.internal.cocoa.NSDictionary

我正在测试的代码是:

public static void main(String[] args) throws Exception {
    NSAutoreleasePool pool = (NSAutoreleasePool)new NSAutoreleasePool().alloc().init();

    //read the test data into a byte array
    int read = 0;
    byte[] buffer = new byte[1024];
    FileInputStream in = new FileInputStream(INPUT);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    while((read = in.read(buffer)) != -1) {
        bytes.write(buffer, 0, read);
    }
    buffer = bytes.toByteArray();

    System.out.println("Read " + buffer.length + " bytes");

    //load the byte array into an NSData instance
    NSData data = NSData.dataWithBytes(buffer, buffer.length);

    //deserialize the data              
    id result = NSKeyedUnarchiver.unarchiveObjectWithData(data);

    //error here
    NSDictionary dictionaryResult = (NSDictionary)result;

    pool.release();
}

那么我需要做什么才能将“结果”从 id 转换为更有用的内容,例如 NSDictionary

最佳答案

呸,没关系,我已经明白了。从 id 获取 SWT 中可用的内容的方法是构造所需具体类型的新实例,并将 id 作为参数传递给构造函数。喜欢:

NSDictionary dictionaryResult = new NSDictionary(result);

当你仔细想想时,就很明显了。

关于java - Eclipse SWT - 如何从 'id' 转换为可用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815611/

相关文章:

ios - 在后台加载数据并重新加载tableView

java - 如何在Eclipse中创建单元测试项目?

java.lang.NullPointerException : Cannot invoke "jdk.internal.platform.CgroupInfo.getMountPoint()" because "anyController" is null

iphone - 找不到库-命令/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2失败,退出代码为1

iphone - Objective-C 包级属性

ios - 为什么协议(protocol)在 swift 中优于类?

ios 谷歌 api 问题

java - 尝试从 "main-menu"类调用方法,但它被卡住了,但是当从方法类调用时,它工作得很好

java - 为什么我会收到此泛型类型的未经检查的转换警告?

iOS UITableView - 向左滑动并单击单元格时显示删除按钮