0
@Entity
class Student{
 @NotNull
 private int sid;
 @NotNull
 private String sname;
 private int age;
}

i have to show the name of the field that contain @NotNull annotation

I created a function

public boolean hasNotNull() {
        return Arrays.stream(this.getClass().getDeclaredFields())
                .anyMatch(field -> field.isAnnotationPresent(NotNull.class));
    }

public Object[] getValue() {
        if (hasNotNull())

            return Arrays.stream(this.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(NotNull.class)).toArray();

        else
            return null;
    }

But I am getting the 500 Internal Server Error.

Following are the warnings:

WARNING: An illegal reflective access operation has occurred
WARNING: Please consider reporting this to the maintainers of com.fasterxml.jackson.databind.util.ClassUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

What should I do?

Bhumika
  • 45
  • 2
  • 10
  • If you are getting 500 error, there should be an exception on the server side logs. Can you please attach the exception stack trace? But my guess is that you're using the result of calling getValue() and treat it as an array - without null check (getValue can return null). Perhaps you want to return an empty array instead? – Ondra K. Feb 22 '21 at 08:56
  • 1
    Generally returning `Object[]` is not a good idea. `Field[]` would be better, also returning `null` for arrays or collection is almost always not what you intended, using an empty array `return new Field[0];` is way better – Lino Feb 22 '21 at 08:58
  • @Lino if i use Field[], then a nnew eroor occured i.e. Type mismatch: cannot convert from Stream to Field[] – Bhumika Feb 22 '21 at 09:01
  • @OndraK. Please find the attached warnings – Bhumika Feb 22 '21 at 09:02
  • @Bhumika you need to change the `toArray()` method to `toArray(new Field[0])` or when you're using a later java version (I think Java11) you can use `toArray(Field::new)` – Lino Feb 22 '21 at 09:34

2 Answers2

0
public List<String> getValue() {

        if (hasNotNull()) {
            Stream<Field> filter = Arrays.stream(this.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(NotNull.class));
            return filter.map(obj -> obj.getName()).collect(Collectors.toList());
        }

        else
            return null;
    }
Bhumika
  • 45
  • 2
  • 10
-1

Since you get the declared fields, you working with private fields that you normally can't access. Use .setAccessible on the field before calling another method on it

Tokazio
  • 516
  • 2
  • 18