Very simple Java Dynamic Casting

后端 未结 3 682
慢半拍i
慢半拍i 2021-01-18 16:03

Simple question but I have spent over an hour with this. My code is below. I need to make SomeClass sc dynamic. So you pass the class name as a string in a function and use

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 16:38

    The problem you're describing is not well defined. Casting is an operation that takes an object and a Class and then checks if that object is an instance of the given class.

    However you're saying you need something that cast(s) the classname referred by strClassName to SomeClass if it is the instance of SomeClass. In other words, you're looking something that works on two classes (rather than a class and an object).

    So, we need to restate the problem. Here are three possible problems (+ solutions) I'm hoping one of them is what you need

    // Problem 1: check whether "object" can be casted to the class 
    // whose name is "className"
    public void castDynamic(Object object, String className) {
      Class cls = Class.forName(className);
      cls.cast(object);
    }
    
    // Problem 2: check whether the class whose name is "className" 
    // is a subclass of SomeClass (A is a subclass of B if A (transitively) 
    // extends or implements B).
    public void castDynamic(String className) {
      Class cls = Class.forName(className);
      SomeClass.class.asSubclass(cls);
    }
    
    
    // Problem 3: check whether SomeClass is a sublcass the class 
    // whose name is "className"
    public void castDynamic(String className) {
      Class cls = Class.forName(className);
      cls.asSubclass(SomeClass.class);
    }
    

    Full details: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#asSubclass(java.lang.Class)

提交回复
热议问题