Force compiler to emit checkcast for upcast [message #1738700] |
Fri, 22 July 2016 08:11  |
Eclipse User |
|
|
|
Hi,
is it possible to force the compiler to emit a (redundant) checkcast when performing an upcast (rather than a downcast)?
And in case you are wondering why one would want such a thing: I am implementing a JDT ASTVIsitor, which should work both with JDT versions aware (post 3.10) and unaware (pre 3.10) of Java 8 features like lambda expressions.
public boolean visit(LambdaExpression node) {
node.resolveTypeBinding(); // (1) invokevirtual LambdaExpression.resolveTypeBinding()
helper(node); // (2) invokespecial MyVisitor.helper(Expression)
return super.visit(node); // (3) invokespecial ASTVisitor.visit(LambdaExpression)
}
private void helper(Expression node) { }
The Java VM is able to verify (without having to load the LambdaExpression class not present in pre 3.10 JDTs) by type-checking the calls (1) and (3) but not call (2), as it cannot know that LambdaExpression is a subtype of Expression. I would need to explicitly cast the argument to helper to Expression in order for the above to pass verification (without having to load LambdaExpression).
|
|
|
|
Re: Force compiler to emit checkcast for upcast [message #1738814 is a reply to message #1738766] |
Mon, 25 July 2016 03:35  |
Eclipse User |
|
|
|
Stephan Herrmann wrote on Sat, 23 July 2016 11:03You are relying on the fact that pre 3.10 this method will never get called, and you just want to avoid verification errors, is that it?
Yes, that's it; I know that a pre3.10 JDT's ASTNode.accept(ASTVisitor) will never visit a LambdaExpression, but I need to make sure that MyVisitor can load without the JVM trying to resolve LambdaExpression during the verification of the MyVisitor.visit(LambdaExpression) method.
Quote:Would the following kludge work?
Object o = node:
helper( (Expression) o);
(No, the compiler has no such option for inserting unnecessary casts).
That does the trick. Thank you.
FYI, JDT Core is a nice API to work with when you still have support older versions of the JDT in the same codebase, as code like the following (and the aforementioned visit methods) only requires a new JDT to compile, but not to run:
switch (node.getNodeType)) {
case ASTNode.LAMBDA_EXPRESSION:
LambdaExpression lambda = (LambdaExpression) node;
// Do JDT 3.10+ stuff with lambda
break;
}
It's quite well designed in that respect. Kudos!
|
|
|
Powered by
FUDForum. Page generated in 0.05190 seconds