The problem is that the compiler cannot determine the information of the myArray array during compilation. It is considered common because (as the eclipse shows) it is converted to {new GenericClass <T> .MyClass (), ...}. This is because you put the MyClass class inside a common class.
This code does not work:
package my.stuff; public class GenericClass<T> { class MyClass { static MyClass[] myArray = { new MyClass(), new MyClass() };; } public GenericClass(final T[] param) { MyClass myObject = new MyClass(); } }
but this code works:
package my.stuff; public class GenericClass<T> { public GenericClass(final T[] param) { MyClass myObject = new MyClass(); MyClass[] myArray = { new MyClass(), new MyClass() }; } } class MyClass { }
Since you are not using generics in your MyClass, it is best to probably do the second.
If you declare it static, the compiler knows that MyClass is not shared, and it knows what to do.
In addition, the only way to create a shared array in java is to create a raw type and then pass it to generics (see here: "Cannot create a shared array .."; - how to create an array from Map <String, Object>? ). So, if you absolutely need myClass inside the generic, you have to rotate it to MyClass <T>, and then use the trick: create a raw type and pass it to MyClass <T>:
package my.stuff; public class GenericClass<T> { class MyClass<T> { } @SuppressWarnings("unchecked") public GenericClass(final T[] param) { MyClass<T> myObject = new MyClass<T>(); MyClass<T>[] myArray = new MyClass[]{ new MyClass<T>(), new MyClass<T>() }; } }
even if you are not using T inside the MyClass class.
source share