简体   繁体   English

自动类型铸造

[英]Automatic type casting

I have a program that needs to accept objects of which the class types are only known at runtime.我有一个程序需要接受类类型仅在运行时才知道的对象。 I was wondering if it's possible to have the program automatically cast back the objects to the correct class type?我想知道是否有可能让程序自动将对象转换回正确的类类型?

The following code is what I currently have;以下代码是我目前拥有的; I will explain what I expect it to do step-by-step:我将逐步解释我期望它做什么:

  1. Create a TryingSomething instance that adds two sets (one of class type Foo , one of class type Bar ).创建一个TryingSomething实例,该实例添加两个集合(一个是类类型Foo ,一个是类类型Bar )。
  2. The sets are supposed to be added to the hashmap.这些集合应该被添加到哈希图中。 At this point I already get a warning from Eclipse, warning me that the sets are not compatible somehow.在这一点上,我已经收到来自 Eclipse 的警告,警告我这些集合以某种方式不兼容。 The types are the same though.不过类型是一样的。 What went wrong here?这里出了什么问题?
  3. Moving on, assuming the previous step did work as intended.继续,假设上一步确实按预期工作。 I wish to retrieve the collections in the main method again, but already cast to the correct class types ( Foo and Bar ).我希望再次检索 main 方法中的集合,但已经转换为正确的类类型( FooBar )。 Will this work?这会起作用吗? If not, is there an alternative that allows me to retrieve the objects back in their correct class type?如果没有,是否有替代方法可以让我以正确的类类型检索对象?
  4. (Bonus) The name String that's attached with each collection, is introduced to allow me to distinguish between the different class types. (奖励)每个集合附带的名称 String 被引入以允许我区分不同的类类型。 It would be even better if it was possible to achieve the results in step 3, without needing the String.如果可以实现步骤 3 中的结果,而无需 String。

Thanks to anyone who can give me some pointers.感谢任何可以给我一些指示的人。

class TryingSomething<T> {
    private Map<String, Set<T>> map = new HashMap<String, Set<T>>();

    public void addCollection(Set<T> s, String name){
        this.map.put(name, s);
    }

    public void test(){
        Set<Foo> foo = new HashSet<Foo>();
        Set<Bar> bar = new HashSet<Bar>();
        addCollection(foo, "foo");
        addCollection(bar, "bar");
    }

    public Set<T> getCollections(String name){
        return this.map.get(name);
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args){
        TryingSomething t = new TryingSomething();
        Set<Foo> foo = new HashSet<Foo>();
        Set<Bar> bar = new HashSet<Bar>();
        t.addCollection(foo, "foo");
        t.addCollection(bar, "bar");
        Set<Foo> fooList = t.getCollections("foo");
        Set<Bar> barList = t.getCollections("bar");
    }

}

class Foo{
}

class Bar{
}

You can use the class objects (runtime types) of the classes for your map keys:您可以将类的类对象(运行时类型)用于映射键:

class TryingSomething {
    private Map<Class<?>, Set<?>> map = new HashMap<>();

    public <T> void addCollection(Set<T> s, Class<T> clazz){
        map.put(clazz, s);
    }

    public void test(){
        Set<Foo> foo = new HashSet<Foo>();
        Set<Bar> bar = new HashSet<Bar>();
        addCollection(foo, Foo.class);
        addCollection(bar, Bar.class);
    }

    @SuppressWarnings("unchecked")
    public <T> Set<T> getCollections(Class<T> clazz){
        return (Set<T>)this.map.get(clazz);
    }


    public static void main(String[] args){
        TryingSomething t = new TryingSomething();
        Set<Foo> foo = new HashSet<Foo>();
        Set<Bar> bar = new HashSet<Bar>();
        t.addCollection(foo, Foo.class);
        t.addCollection(bar, Bar.class);
        Set<Foo> fooList = t.getCollections(Foo.class);
        Set<Bar> barList = t.getCollections(Bar.class);
    }

}

class Foo{
}

class Bar{
}

The class TryingSomething shouldn't be generic because you want to store sets of arbitrary types (chosen dynamically at runtime). TryingSomethingTryingSomething应该是泛型的,因为您要存储任意类型的集合(在运行时动态选择)。 Note that this implementation does not check if an inserted set actually contains objects of the specified type at all (neither at insertion nor at retrieval) - the reponsibility here lies with the user of this container class.请注意,此实现根本不检查插入的集合是否实际包含指定类型的对象(无论是在插入时还是在检索时)——这里的责任在于此容器类的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM