My goal is to check the type of messages
and then accordingly convert them to Strings and add them. How can I achieve this?
public void addMessages(List<?> messages) {
if (messages != null) {
if (messages instanceof String) {
for (String message : messages) {
this.messages.add(message);
}
}
}
else {
for (Object message:messages) {
this.messages.add(String.valueOf(message));
}
}
}
You can just pass in a List of Objects - you don't even need the if/else since you can just always call "toString()" or "String.valueOf" on the message object:
public void addMessages(List<Object> messages) {
if (!CollectionUtils.isEmpty(messages)) {
for (Object message : messages) {
this.messages.add(String.valueOf(message));
}
}
}
On a side note: Potential problems could arise from having null elements in the messages list - so you might want to check for that in your loop. Other potential pitfalls are:
NullPointerException
public void addMessages(List<Object> messages) {
这就足以让messages
所有类型的对象。
You can achieve that with "Java Generics".
The Messages
object initialized in the main method below will accept the list of objects of any type. You can initialize Messages
object with a specific type as well.
public class Messages<T> {
private List<T> messages = new ArrayList<T>();
public void addMessages(List<T> messages) {
for (T message : messages) {
// Use String.valueOf or message.toString()
// if you would like to convert the objects to String.
}
}
public static void main(String[] args) {
Messages<Object> msg = new Messages<Object>();
msg.addMessages(/** Your List of objects of any type **/);
}
}
This is just an enhancement over the answers by nutfox.
public void addMessages(List<?> messages) {
List<String> collect = messages.stream().map(i -> String.valueOf(i)).collect(Collectors.toList());
this.messages.addAll(collect);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.