Skip to content

Instantly share code, notes, and snippets.

@tksmaru
Created January 23, 2014 07:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tksmaru/8574444 to your computer and use it in GitHub Desktop.
Save tksmaru/8574444 to your computer and use it in GitHub Desktop.
package org.tksmaru.playgound;
import java.lang.reflect.Constructor;
public class ActiveClassWithReflection {
private enum ErrorType {
LESS_MONEY("less.money", UserException.class),
NO_STOCK("no.stock", ShopException.class),
SHOP_CLOSE("shop.close", ShopException.class);
private String message;
private Class<? extends Exception> ex;
private ErrorType(String message, Class<? extends Exception> ex) {
this.message = message;
this.ex = ex;
}
String getMessage() {
return message;
}
Exception getException() {
Class<? extends Exception> clazz = this.ex;
try {
// 引数がmessageのコンストラクタからインスタンスを生成する
Constructor<? extends Exception> constructor = clazz.getConstructor(String.class);
return constructor.newInstance(this.message);
} catch (Exception e) {
return new Exception("Invokation error.", e);
}
}
}
public void throwExceptionByErrorType(ErrorType error) throws UserException, ShopException, Exception {
throw error.getException();
}
public static void main(String [] args) {
ActiveClassWithReflection2 test = new ActiveClassWithReflection2();
try {
test.throwExceptionByErrorType(ErrorType.LESS_MONEY);
} catch (UserException e) {
System.out.println("UserException:" + e.getLocalizedMessage());
} catch (ShopException e) {
System.out.println("ShopException:" + e.getLocalizedMessage());
} catch (Exception e) {
System.out.println("Exception:" + e.getLocalizedMessage());
}
try {
test.throwExceptionByErrorType(ErrorType.NO_STOCK);
} catch (UserException e) {
System.out.println("UserException:" + e.getLocalizedMessage());
} catch (ShopException e) {
System.out.println("ShopException:" + e.getLocalizedMessage());
} catch (Exception e) {
System.out.println("Exception:" + e.getLocalizedMessage());
}
}
static class ShopException extends Exception {
public ShopException(String message) {
super(message);
}
}
static class UserException extends Exception {
public UserException(String message) {
super(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment