I have two a conditions in the method:
if(urlSendModel.isHasPhoto()) {
ArrayList<InputMediaPhoto> inputMediaPhotos = new ArrayList<>();
for(String photoUrl : urlSendModel.getPhotos()){
inputMediaPhotos.add(new InputMediaPhoto(photoUrl));
}
SendMediaGroup sendMediaGroup = new SendMediaGroup(message.chat().id(),
inputMediaPhotos.toArray(new InputMediaPhoto[0]));
bot.execute(sendMediaGroup);
}
if(urlSendModel.isHasVideo()){
ArrayList<InputMediaVideo> inputMediaVideos = new ArrayList<>();
for(String videoUrl : urlSendModel.getVideos()){
inputMediaVideos.add(new InputMediaVideo(videoUrl));
}
SendMediaGroup sendMediaGroup = new SendMediaGroup(message.chat().id(),
inputMediaVideos.toArray(new InputMediaVideo[0]));
bot.execute(sendMediaGroup);
}
How can I create something like this or solve the problem in another way.
private <T extends InputMedia<T>> void sendMedia(Message message, ArrayList<String> urls) {
ArrayList<T> inputMedia = new ArrayList<>();
for(String url : urls){
inputMedia.add(new T(url));
}
SendMediaGroup sendMediaGroup = new SendMediaGroup(message.chat().id(),
inputMedia.toArray(new T[0]));
bot.execute(sendMediaGroup);
}
I will be glad to any proposed solution.
new Tby having the client specify a class literal, then callinggetConstructor(...).newInstance(...). But this will not work for creating a generic array. You'd have to pass the responsibility of creating these objects to the client:sendMedia(message, urls, InputMediaVideo::new, () -> new InputMediaVideo[0]);, declaring the method as<T extends InputMedia<T>> void sendMedia(Message, Function<String, T>, Supplier<T[]>)Array.newInstance(klass, length);(and pass in theclass) which might be more understandable when reading.