协助将Java转换为Objective-C

协助将Java转换为Objective-C,java,objective-c,Java,Objective C,我正试图将一些代码从Java转换成Objective-C,但我在转换Java通用部分时遇到了困难。例如,我相信Java中的类声明是说当前类扩展了组件类的子类,在Objective-c中,这是否意味着只扩展组件类 如果有人能提供任何帮助,我们将不胜感激。继续这样做将帮助我转换其他类似的代码片段。谢谢 爪哇: public class ComponentMapper<T extends Component> { private Class<T> classType; pu

我正试图将一些代码从Java转换成Objective-C,但我在转换Java通用部分时遇到了困难。例如,我相信Java中的类声明是说当前类扩展了组件类的子类,在Objective-c中,这是否意味着只扩展组件类

如果有人能提供任何帮助,我们将不胜感激。继续这样做将帮助我转换其他类似的代码片段。谢谢

爪哇:

public class ComponentMapper<T extends Component> {

private Class<T> classType;

public ComponentMapper(Class<T> type, World world) {
    this.type = ComponentTypeManager.getTypeFor(type);
    this.classType = type;
}

public T get(Entity e) {
    return classType.cast(em.getComponent(e, type));
}
}
例如,我相信Java中的类声明表示当前类扩展了组件类的子类

不,
ComponentMapper
表示类
ComponentMapper
可以用扩展
Component
(或
Component
本身)的任何类参数化。因此,您可以执行
新组件映射器
等操作

在运行时,泛型信息被擦除,从而产生一个
组件映射器(ComponentMapper
),即编译器将
public T get(Entity e)
视为
public MySpecialComponent get(Entity e)
,而在运行时类型擦除后,它只是
public Component get(Entity e)


除此之外,
ComponentWrapper
Component
有一个has-a关系,即
ComponentWrapper
有一个类型为
Component.class
的成员(或
class
,意思相同:不是
Component
实例,而是对类本身的引用)。扩展将是一种is-a关系。

创建Java泛型是为了向集合和参数化类添加编译时类型安全性。在像Java这样的静态类型语言中,这是非常有用的,但在动态类型且具有动态调度的Objective C中更是如此


我建议您在从Java转换时只需删除泛型占位符,并用id替换泛型返回类型/参数。

使用
Class
是Java中的一个习惯用法,它旨在消除Java泛型的类型擦除。在这种情况下,你应该非常小心地避免翻译成语“逐字逐句”,因为在这些地区,以废话结尾的几率非常高。最好的方法是尝试使用现有设计作为新项目的灵感,而不是模板。当我将Java翻译成C#时,它对我来说非常有效——诚然,这是一个非常接近的匹配,但仍然足以证明主要的重构是正确的。好的,这意味着ComponentMapper包含一个组件列表或组件的子类型?所以在Obj-c中,我不应该扩展组件,而是保留对它的引用?@user1106500我不知道,因为缺少一些代码(
World
未使用,
em
未声明等)。看起来包装器实际上只是从某处获取组件(是
em
一个
EntityManager
?)并将其强制转换。根据em.getComponent(e,type)的实际情况,您可能需要另一个解决方案,或者根本不需要
ComponentWrapper
。让我陈述一件重要的事情:在您尝试将代码移植到另一种语言之前,您应该知道它实际上做了什么,而不仅仅是猜测。因此,首先理解Java代码的逻辑,然后将其移植到Objective-C。
@interface ComponentMapper : Component
{
    ComponentType* componentType;
    EntityManager* entityManager;
    id classType;
}

- (id) init:(id) componentType World:(World*) world;
- (id) get:(Entity*) entity; // can this just return Entity instead

@end

@implementation ComponentMapper 

- (ComponentMapper*) init:(id) type World:(World *) world {
    if (self = [super init]) {
        // should be a call to getEntityManager()
        self->entityManager = [world entityManager];
        self->componentType = [ComponentTypeManager getTypeFor:type];
        self->classType = type;
    }

    return self;
}

- (id) get:(Entity*) entity
{
    return [classType cast:[em getComponent:e param1:type]];
}

@end