Bazaprogram.ru

Новости из мира ПК
1 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java lang unsupportedoperationexception

Как побороть UnsupportedOperationException: null в Spring?

Столкнулся с довольно странной проблемой. Имеется entity User и объекты этого класса нужно связать друг с другом через many-to-many relationship. Соответственно, помимо основной таблицы «user» должны появиться еще 2 таблицы «customer_authors» «author_customers»

Нигде в моем коде не используется Arrays asList() / не создается список с фиксированным размером. Именно, это является причиной подобной ошибки согласно поиску в гугл и stackoverflow.

В моем случае, если в @Service UserService использовать подобный код:

то получаю соответствующую ошибку —

Но при этом, если для теста в контроллере использовать что-то подобное:

то действительно, в таблицу добавляется нужная информация ID реферрера и ID пользователя.

В чем может быть заключаться ошибка? Может быть, кто-то сталкивался с этим и знает, как исправить? Заранее благодарю!

Полный сниппет метода из UserService:

2 ответа 2

Откуда взялся UnsupportedOperationException?

Коллекции в Java могут иметь необязательные для реализации методы.
При вызове метода, имплементация которого не предусмотрена в данной реализации выбрасывается UnsupportedOperationException :

Наличие подобных методов в интерфейсе может вызвать недоумение, однако в данном случае, насколько я понимаю, это вызвано поддержкой обратной совместимости с более старыми версиями Java.

Как уже говорилось другими участниками, коллекции могут быть изменяемыми и неизменяемыми. Однако, вопреки общему мнению в данном случае исключение возникает не из-за использования Arrays.asList (автор явно инициализирует поля новым объектом ArrayList’а ).
Хотя это было очень-очень близко и копать явно нужно было в эту сторону.

К сожалению, всё внимание было приковано к двум полям: authorsList и customersList .
Там были очень сомнительные зеркальные связи, да ещё и с каскадными операциями, которые в данном конкретном случае явно не могли быть применены в том виде. Более того при удалении cascade=CascadeType.ALL ошибка пропадала. К ним мы вернемся позже.

Ошибка была куда прозаичнее:

Автор явно создаёт синглтон(немодифицируемую коллекцию) и передаёт его в список ролей.

После чего данный объект успешно сохраняется.

Ошибка же возникает после того как мы добавляем данного пользователя в список приглашенных клиентов другого пользователя и сохраняем второго пользователя(приглашающего), который был предварительно получен с помощью hibernate.

Сохранив второго пользователя и его связь с первым, hibernate смотрит на cascade=CascadeType.ALL над customersList и начинает обновлять объект первого пользователя, который лежал в данном списке. Перезаписывает все поля, встречающиеся в полях коллекции hibernate чистит после чего извлекает в них данные заново. И так он доходит до поля roles с синглтоном, который лежит в первом пользователе, который в свою очередь лежит внутри списка второго пользователя. Пытается очистить его и получает UnsupportedOperationException .

Чтобы исправить это достаточно просто написать:

И cascade=CascadeType.ALL в данном случае не при чем.
Тем не менее его оставлять так нельзя. Потому что, при удалении приглашающего пользователя автоматически будут удалены и все авторы и клиенты, что как мне кажется не соответствует замыслам автора.

Над данными двумя полями( authorsList и customersList ) стоит как минимум поставить

А если говорить честно, то данные поля являются избыточными и от них можно просто избавиться.
Ведь для каждого приглашенного пользователя мы устанавливаем referrer(пригласившего пользователя).
Соответственно мы можем либо добавить обратное свойство invitedUsers и отфильтровать его по роли.
Либо просто выбрать пользователей по referrer’у и роли.

Java List UnsupportedOperationException

Last modified: July 19, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

In this quick tutorial, we’ll discuss a common Exception that can occur when working with some the API of most List implementations – the UnsupportedOperationException.

A java.util.List has more functionality than an ordinary array can support. For instance, with only one built-in method call, it’s possible to check if a specific element is inside the structure. That’s typically why we sometimes need to convert an array to a List or Collection.

For an introduction to the core Java List implementation – the ArrayList – please refer to this article.

Читать еще:  Программа для проверки и восстановления жесткого диска

2. UnsupportedOperationException

A frequent way in which this error occurs is when we use asList() method from java.util.Arrays:

  • a fixed-size List as of size of a given array
  • an element of the same type as the one in the original array and it must be an Object
  • elements in the same order as in original array
  • a list that is serializable and implements RandomAccess

Since T is a varargs, we can pass an array or the items directly as parameters, and the method will create a fixed-size initialized list:

We can also pass an actual array:

Since the returned List is a fixed-size List, we can’t add/remove elements.

An attempt to add more elements would cause UnsupportedOperationException:

The root of this Exception is that the returned object doesn’t implement the add() operation since it isn’t the same as java.util.ArrayList.

It’s an ArrayList, from java.util.Arrays.

Another way to obtain the same exception is by trying to remove an element from the obtained list.

On the other hand, there are ways to obtain a mutable List in case we need it.

One of them is to create an ArrayList or any kind of list directly from the result of asList():

3. Conclusion

In conclusion, it’s important to understand that adding more elements to a list can be problematic for more than just immutable lists.

As always, the full source code of the examples is available over on GitHub.

Java Exception Handling – UnsupportedOperationException

Making our way through our detailed Java Exception Handling series, today we’ll dive into the UnsupportedOperationException. The UnsupportedOperationException is used by a number of built-in Java methods to indicate that the method in question is not currently implemented. This is functionally similar to exceptions found in other languages, such as the .NET NotImplementedException we explored in a previous article.

In today’s article we’ll examine the UnsupportedOperationException in more detail, beginning with a dive into where it sits in the overall Java Exception Hierarchy. We’ll also go over a handful of functional code samples illustrating how UnsupportedOperationExceptions can be thrown in the standard Java library, along with how you might consider using them in your own code, so let’s get started!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

This code sample also uses the Book.java class, the source of which can be found on GitHub.

It also uses the Logging.java class, the source of which can be found on GitHub.

When Should You Use It?

The overall purpose of the UnsupportedOperationException is to indicate that the called method is not implemented or supported at present. This might be due to ongoing development, which has to yet to finish the method. Another common use for the UnsupportedOperationException is when the called method is required due to implementation of an interface , yet invoking said method would be considered improper or invalid. This is similar behavior to the .NET InvalidOperationException that we looked at a few months ago.

No matter what the intention is, throwing an UnsupportedOperationException is the primary means of indicating that a method is not supported and should produce an error. To illustrate this behavior we’ll start with some of the built-in Java library usage of the UnsupportedOperationException . A common collection of classes that make heavy use of this exception are, well, the Collection -interfaced classes. There are many types of collections within the standard library, and many of them share the same interface implementations, yet they don’t all wish to allow the same functionality.

As an example, imagine that you need a collection that is unmodifiable (i.e. immutable ). To accomplish this you might look to the AbstractList class. Since this is an abstract class we must imeplement it ourselves in our own class, so we’ll do so in the DefaultAbstractList class:

Читать еще:  Как отключить точку восстановления в windows 10

As it happens, if we simply need to create an immutable list from AbstractList , we merely need to extend the class and override the get(int index) and size() methods, as seen above. Now we can test our DefaultAbstractList out. We’ll be creating a Book instance and attempting to add that element to our DefaultAbstractList instance. Our addBookToList(Book book, AbstractList list) helper method will make this process easier to repeat:

Since AbstractList is a parent class of our DefaultAbstractList class, we’re able to specify it as the expected parameter type of our method, allowing us to pass other class instances that extend AbstractList later on. Otherwise, the functionality of addBookToList(. ) is fairly simple: We start by outputting the book info and list class we’re attempting to add it to. Then we call the add(int index, E element) method of the list parameter. Finally, we output the modified list information, including the newly added element.

To test this out our Main.main(. ) method creates a new DefaultAbstractList instance, then attempts to add a new Book instance to it via addBookToList(. ) :

If you’re familiar with using AbstractLists already, you may see what’s coming. Executing the test code above produces the following output:

Here we catch our first UnsupportedOperationException which, unfortunately, fails to provide much useful information since there’s no associated error message. A bit of digging reveals that the issue is that, while the AbstractList includes the add(int index, E element) method, it intentionally throws an UnsupportedOperationException when invoked. This is because calling an add(. ) method of any collection indicates that the collection should be changeable ( mutable ), which we did not plan for in our DefaultAbstractList class.

To resolve this we’ll create another class that is designed to handle mutable lists, MutableAbstractList :

Our MutableAbstractList class actually includes some basic collection functionality. We’ve added a private ArrayList list property, along with implementation of the add(int index, E element) , get(int index) , and size() methods. Once again, let’s test this out by creating another new Book instance and attempting to add it to a new MutableAbstractList :

This time we have no trouble invoking the add(int index, E element) method to add our new Book instance, which results in the expected output showing the book being added to the collection:

That’s cool and we’ve now seen how the standard Java library sometimes throws UnsupportedOperationExceptions to indicate invalid method calls. However, let’s look briefly at how we might throw an UnsupportedOperationException in our own code, under the right circumstances. To accomplish this we’ll look at our last custom class, aptly named ImmutableList :

Functionally this class is similar to the MutableAbstractList except, as the name suggests, it shouldn’t allow collection elements to be modified. Thus, both implementations of the add(. ) method in this class intentionally throw an UnsupportedOperationException . Unlike the standard Java throws we saw earlier, we’ve opted to include some more useful information in the error message.

Although subtle, we have to use a slightly different addBookToList(. ) method signature than before, since ImmutableList doesn’t extend the AbstractList class that our previous examples did. Attempting to use the addBookToList(Book book, AbstractList list) method signature with an ImmutableList argument would result in a compilation error, so we’re using this second method signature instead:

Otherwise, our call to addBookToList(. ) is much the same as before:

As expected and intended, executing the above results in a thrown UnsupportedOperationException , which includes our detailed error message:

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Читать еще:  Как восстановить инстаграм если забыла электронную почту

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!

java.lang.UnsupportedOperationException – How to handle UnsupportedOperationException

In this tutorial we will discuss about UnsupportedOperationException in Java. This exception is thrown to indicate that the requested operation is not supported.

This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause. Moreover, the UnsupportedOperationException exists since the 1.2 version of Java.

The Structure of UnsupportedOperationException

Constructors

  • UnsupportedOperationException()

Creates an instance of the UnsupportedOperationException class, setting null as its message.

UnsupportedOperationException(String s)

Creates an instance of the UnsupportedOperationException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

UnsupportedOperationException(String message, Throwable cause)

Creates an instance of the UnsupportedOperationException class, using the specified parameters as message cause respectively.

UnsupportedOperationException(Throwable cause)

Creates an instance of the UnsupportedOperationException class, using the specified Throwable as cause. Also, the Throwable::toString() method specifies the message of the exception.

The UnsupportedOperationException in Java

The UnsupportedOperationException indicates that the requested operation cannot be performed, due to the fact that it is forbidden for that particular class. The following methods create unmodifiable views of different collections:

Returns an unmodifiable view of the specified Collection .

Returns an unmodifiable view of the specified Set .

Returns an unmodifiable view of the specified SortedSet .

Returns an unmodifiable view of the specified List .

Returns an unmodifiable view of the specified Map .

Returns an unmodifiable view of the specified SortedMap .

These views are read-only and thus, cannot be modified. If an application tries to modify such view, an UnsupportedOperationException is thrown. The following examples indicate the aforementioned cases:

In this example, we created an instance of the HashSet class, which implements the Collection interface, and inserted a number of random values. Then, we retrieved an unmodifiable view of the Collection and tried to insert a new element, which resulted to an UnsupportedOperationException .

In this example, we created an instance of the HashSet class and inserted a number of random values. Then, we retrieved an unmodifiable view of the HashSet and tried to insert a new element, which resulted to an UnsupportedOperationException .

In this example, we created an instance of the TreeSet class and inserted a number of random values. Then, we retrieved an unmodifiable view of the TreeSet and tried to insert a new element, which resulted to an UnsupportedOperationException .

In this example, we created an instance of the ArrayList class and inserted a number of random values. Then, we retrieved an unmodifiable view of the ArrayList and tried to insert a new element, which resulted to an UnsupportedOperationException .

In this example, we created an instance of the HashMap class and inserted a number of random values. Then, we retrieved an unmodifiable view of the HashMap and tried to insert a new element, which resulted to an UnsupportedOperationException .

In this example, we created an instance of the TreeMap class and inserted a number of random values. Then, we retrieved an unmodifiable view of the TreeMap and tried to insert a new element, which resulted to an UnsupportedOperationException .

How to deal with the UnsupportedOperationException

  • This exception is easy to deal with, because it indicates which method cannot be used. Thus, if your application requires the modification of some collection or data structures, you shall avoid using unmodifiable views.
  • Also, if this exception is thrown by a class of an external library, you shall consult its documentation, in order to understand why this particular exception is thrown.

Download the Eclipse Project

This was a tutorial about the UnsupportedOperationException in Java.

Ссылка на основную публикацию
Adblock
detector