1

what i want to achieve is add Generic in my exception class which is looked like this before :

@ResponseStatus(HttpStatus.NOT_MODIFIED)
public class ResourceGeneralErrorTest extends RuntimeException {
    
    public ResourceGeneralErrorTest(String message){
        super(message);
    }

}

and i use it like this :

throw new ResourceGeneralError("Some error string " + errorTransDoMsg.toString());

but i only can pass string value inside this class. I want to pass Object class in this, so i try to add this :

@ResponseStatus(HttpStatus.NOT_MODIFIED)
public class ResourceGeneralErrorTest<T> extends RuntimeException {

    private T data;
    
    public ResourceGeneralErrorTest(String message){
        super(message);
    }

}

which is give me error when i extends the RuntimeException class, here is the error message Generic class may not extend 'java.lang.Throwable' how can i keep extends RuntimeException and i can pass some object into it with my String message?

Ke Vin
  • 3,478
  • 11
  • 60
  • 91
  • You need to add your own constructor to your class which can accept extra params and then from inside that constructor, call super constructor passing message and also initialising your values. – code_mechanic Mar 23 '21 at 01:31
  • You can't, see here https://stackoverflow.com/q/501277/1876620 – fps Mar 23 '21 at 02:09

1 Answers1

1

Your example should work, you just need to do something like this

public class ResourceGeneralErrorTest extends RuntimeException {

    private Object data;
    
    public ResourceGeneralErrorTest(String message , Object error){
        super(message);
        this.data = error;
    }

    public Object getData() {
          return this.data;
    }

}

Edit: I ignored that you were extending RuntimeException, you cannot do that, generic classes not allowed to extend child of Throwable classes, but you can use Object there instead of T.

code_mechanic
  • 1,097
  • 10
  • 16