Link to home
Start Free TrialLog in
Avatar of oleber
oleberFlag for Portugal

asked on

Create an Array of generic Type

I need to create a array of a generic type.

    class CreateArray<ANY_TYPE> {
        ANY_TYPE[] array = new ANY_TYPE[5];
        ANY_TYPE[] createArray(int nLength) {
            return (ANY_TYPE[])java.lang.reflect.Array.newInstance(ANY_TYPE.class, nLength);
        }
    }

bout this codes don't compile.

Is this possible?
How?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Something like this perhaps?

class CreateArray {
      private Class type;
      
      public CreateArray(Class type) {
            this.type = type;
      }

      public Object getArray() {
            return java.lang.reflect.Array.newInstance(type, 1);
      }
}
Avatar of oleber

ASKER

where is the generic in there?
It doesn't need one. You can write it thus if you want:

class CreateArray<E, e> {
...
}
ASKER CERTIFIED SOLUTION
Avatar of profiles_arun
profiles_arun

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oleber

ASKER

I'm speaking ok JAVA 1.5

My class has a generic and I need to return one array of that type.

Like in the example.

I know that I can do Object[]. But that was one of the JAVA 1.4 problems. Not checking types.