Creating an Array of unknown type

前端 未结 3 1022
北恋
北恋 2021-01-05 15:33

I have an object which I must validate values off the problem, some of the attributes of the Objects are arrays of custom objects. Such that it will involve some boring down

相关标签:
3条回答
  • 2021-01-05 16:13

    If you want to have arrays of unknown types, use generics:

     public <T> T[] getAttribArray(Class<T> repeatingGrpClass)
     {
        //get the attribute based on the class (which you might get based on the enum for example)
        return (T[]) getAttrib( repeatingGrpClass.getName() ); //note that you might want to use the class object instead of its name here
     }
    
    0 讨论(0)
  • 2021-01-05 16:25

    As Oli Charlesworth points out, you can not use the variable name to cast. For a generic type, you will have to cast to Object or Object[].

    Also the Object -> Object[] cast looks illegal. You probably just want a straight cast like so:

    public Object[] getAttribArray(RIORepeatingGrpEnum repeatingGrp)
    {
        Object[] grp = (Object[])getAttrib(repeatingGrp.toString());
        return grp;
    }
    
    0 讨论(0)
  • 2021-01-05 16:34

    No, you cannot use a variable (repeatingGrp) as a type.

    There are ways to do "dynamic" casting, but these wouldn't help you. The return type of getAttribArray is Object, which would defeat the point of casting to a particular type.

    And even if you could fix that, it's still not clear what you could do with this mechanism. What do you want to be able to do with the result of getAttribArray()?

    0 讨论(0)
提交回复
热议问题