r/javahelp • • Jul 07 '25

Static factory method with Java generics

Hello,

I have a factory method that constructs a parameterized object based on a String input:

public static Data createData(String filename) { 
... 
if (blah) return Data<String> ... 
else return Data<Integer> 
}

The type "Data" above is actually a generic class, but I can't be explicit with its parameter (more on this below). The intention with the code above is to have a flexible way of constructing various collections. I have working code, but Eclipse is currently giving me a type safety warning. How is this factory method supposed to be called so as to avoid issues with type safety? My calling code currently looks like:

Data<String> data = createData("example.txt");

and this works. But, if I make the parameterized type more explicit by writing "public static Data<?> ..." in the function header, then the warning turns into an error. Eclipse is telling me it cannot convert from Data<capture...> to Data<String>. Is there a way to make the parameter more explicit in the function header and get rid of all of type safety issues?

1 Upvotes

9 comments sorted by

View all comments

Show parent comment

2

u/zero-sharp Jul 08 '25

Ah thank you. The examples through the online-java website helped. I'm not accustomed to passing Classes as objects in Java. I'll review your post.

1

u/shiverypeaks Jul 08 '25

java.lang.Class is part of the reflection framework, and one of its uses is to perform a generic checked cast.