Java 8 Lambda function that throws exception?

后端 未结 26 2098
臣服心动
臣服心动 2020-11-22 03:14

I know how to create a reference to a method that has a String parameter and returns an int, it\'s:

Function         


        
26条回答
  •  爱一瞬间的悲伤
    2020-11-22 03:24

    I had this problem with Class.forName and Class.newInstance inside a lambda, so I just did:

    public Object uncheckedNewInstanceForName (String name) {
    
        try {
            return Class.forName(name).newInstance();
        }
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    

    Inside the lambda, instead of calling Class.forName("myClass").newInstance() I just called uncheckedNewInstanceForName ("myClass")

提交回复
热议问题