下面的代码是延迟加载类实例创建的代码。
public class MyTest {
private static MyTest test = null;
private UniApp uniApp;
private MyTest(){
try{
uniApp = new UniApp("test","test123");
}
catch(Exception e){
e.printStackTrace();
logger.error("Exception " +e+ "occured while creating instance of uniApp");
}
}
public static MyTest getInstance(){
if (test == null){
synchronized(MyTest.class){
if (test == null){
test = new MyTest();
}
}
}
return test;
}
在构造函数中,我正在创建一个UniApp实例,它要求在自己的构造函数中传递用户I、密码。如果我传递了一个错误的uniApp对象的用户I,密码,uniApp就不会被创建。我需要的是-
我在一个不同的类中调用getInstance方法-
MyTest test=MyTest.getInstance();
在这里,我想添加一个条件,如果uniApp的创建失败了,那就去做吧。我该怎么做?通常,如果我试图调用一个方法,该方法在B类的A类中抛出异常,并在B中添加一个条件--如果A类中的方法抛出异常,则执行以下操作。
我怎样才能做到这一点?如果我的问题令人困惑,请告诉我。我可以编辑它:)
发布于 2014-02-05 03:51:10
从您的私有构造函数中抛出一个异常是可以的(参考This SO question,或者快速搜索)。在您的示例中,您正在捕获从new UniApp()
抛出的异常,而不是将其传递--您可以很容易地将该异常传递到食物链中,然后将其传递到您的getInstance()
方法中,然后由谁来调用该单例。
例如,使用您的代码:
private MyTest() throws UniAppException { // Better if you declare _which_ exception UniApp throws!
// If you want your own code to log what happens, keep the try/catch but rethrow it
try{
uniApp = new UniApp("test","test123");
}
catch(UniAppException e) {
e.printStackTrace();
logger.error("Exception " +e+ "occured while creating instance of uniApp");
throw e;
}
}
public static MyTest getInstance() throws UniAppException {
if (test == null) {
synchronized(MyTest.class) {
if (test == null) {
test = new MyTest();
}
}
}
return test;
}
若要创建"if“条件以测试getInstance()
方法是否有效,请使用try/catch块包围对getInstance()
的调用:
...
MyTest myTest;
try {
myTest = MyTest.getInstance();
// do stuff with an instantiated myTest
catch (UniAppException e) {
// do stuff to handle e when myTest will be null
}
...
由于您还没有展示什么是真正的MyTest.getInstance()
,所以我无法告诉您除此之外还应该做什么。
https://stackoverflow.com/questions/21568083
复制相似问题