diff --git a/lucene/core/src/java/org/apache/lucene/search/Query.java b/lucene/core/src/java/org/apache/lucene/search/Query.java index 560df421e6e3..bc3877418e5b 100644 --- a/lucene/core/src/java/org/apache/lucene/search/Query.java +++ b/lucene/core/src/java/org/apache/lucene/search/Query.java @@ -52,12 +52,30 @@ public abstract class Query { new VirtualMethod<>(Query.class, "rewrite", IndexReader.class); private static final VirtualMethod newMethod = new VirtualMethod<>(Query.class, "rewrite", IndexSearcher.class); - private final boolean isDeprecatedRewriteMethodOverridden = - AccessController.doPrivileged( - (PrivilegedAction) - () -> - VirtualMethod.compareImplementationDistance(this.getClass(), oldMethod, newMethod) - > 0); + private final boolean isDeprecatedRewriteMethodOverridden; + + /** Constructor for query classes. */ + public Query() { + var clazz = this.getClass(); + if (clazz.getName().startsWith("org.apache.lucene.")) { + // we know that all Lucene's own classes have been updated to use new API, so reflection is + // not needed + isDeprecatedRewriteMethodOverridden = false; + } else { + isDeprecatedRewriteMethodOverridden = detectDeprectatedRewriteMethodOverridden(clazz); + } + } + + /** Test only method (used to test backwards layer) */ + Query(Void forTestOnly) { + isDeprecatedRewriteMethodOverridden = detectDeprectatedRewriteMethodOverridden(this.getClass()); + } + + private static boolean detectDeprectatedRewriteMethodOverridden(Class clazz) { + final PrivilegedAction action = + () -> VirtualMethod.compareImplementationDistance(clazz, oldMethod, newMethod) > 0; + return AccessController.doPrivileged(action); + } /** * Prints a query to a string, with field assumed to be the default field and diff --git a/lucene/core/src/test/org/apache/lucene/search/TestQueryRewriteBackwardsCompatibility.java b/lucene/core/src/test/org/apache/lucene/search/TestQueryRewriteBackwardsCompatibility.java index a9534b7f191e..7c86e78d83fb 100644 --- a/lucene/core/src/test/org/apache/lucene/search/TestQueryRewriteBackwardsCompatibility.java +++ b/lucene/core/src/test/org/apache/lucene/search/TestQueryRewriteBackwardsCompatibility.java @@ -158,6 +158,10 @@ public Query rewrite(IndexReader reader) throws IOException { private abstract static class RewriteCountingQuery extends Query { int rewriteCount = 0; + RewriteCountingQuery() { + super(null); // enforce usage of backwards compatibility mode + } + abstract RewriteCountingQuery getInnerQuery(); }