Java does not have union types, so a type like A | B is not possible in Java.
Java 15 saw the addition of sealed types via JEP 360, so you can create a sealed type hierarchy with only two types that cannot be extended, effectively simulating union types for your own types.
By passing an instance of Class, you can then use reflection to instantiate the type.
public sealed interface FooBar permits Foo, Bar { }
public final class Bar implements FooBar { }
public final class Foo implements FooBar { }
public FooBar createMethod(Class<? extends FooBar> type) {
return type.newInstance();
}
Without sealed types, you have to live with the fact that 3rd parties might extend your types, thus making more than just the two types possible as parameters for the method.
Another possibility is using Strings, and using Class.forName(String) to get the type associated with the fully qualified class:
public FooBar createMethod(String type) {
if (type.equals("your.type.Foo") || type.equals("your.type.Bar"))
return Class.forName(type).newInstance();
}