> On Nov 4, 2015, at 12:21 AM, Peter Levart <[email protected]> wrote:
>
>>
>> I was not thinking of calling StackWalker::getCallerClass from native, but
>> calling some method from native, which then calls
>> StackWalker::getCallerClass. The method itself can not anticipate how it
>> will be called. Most methods calling getCallerClass will assume their caller
>> is a Java method and won't bother to think of consequences when this is not
>> the case. But any method can be called from native code in a newly attached
>> thread. I'm not saying this is common, but can happen.
>>
>> So the question is whether Thread.class is always the right substitute in
>> such situations and whether it would be better to return null or
>> Optional.empty(). If you don't want to force users to handle the uncommon
>> case then perhaps it's best to return null. They will get NPE in the
>> uncommon case and will be forced to handle it as opposed to using
>> Thread.class which might silently "work", but not do the right thing.
>
> ... additionaly, Thread.class (or a subclass) can not be reliably used as a
> sentinel value to identify such uncommon cases because it can sometimes be a
> legal caller, as in:
>
> public class StackWalkerDemo {
>
> public static void doIt() {
> StackWalker sw = new StackWalker(StackWalker.Option.CLASS_REFERENCE);
> System.out.println("I was called from: " + sw.getCallerClass());
> }
>
> public static void main(String[] args) throws Exception {
> Thread t = new Thread(StackWalkerDemo::doIt);
> t.start();
> t.join();
> }
> }
Good point. If it returns null, users should prepare for it to return null.
So I think returning Optional<Class<?>> is better than null and that would make
it equivalent to:
walk(s -> s.map(StackFrame::getDeclaringClass).skip(2).findFirst());
I have changed the API to return that.
Will post an updated API and webrev once I incorporate most of the comments.
thanks
Mandy