Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions docs/reference-manual/native-image/Reflection.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,15 @@ Here, `reflectconfig` is a JSON file in the following format (use `--expert-opti
{ "name" : "format", "parameterTypes" : ["java.lang.String", "java.lang.Object[]"] }
]
},
{
"name" : "java.lang.String$CaseInsensitiveComparator",
"methods" : [
{ "name" : "compare" }
]
}
{
"name" : "java.lang.String$CaseInsensitiveComparator",
"methods" : [
{ "name" : "compare" }
]
}
]
```

The native image builder generates reflection metadata for all classes, methods, and fields referenced in that file.
The `allPublicConstructors`, `allDeclaredConstructors`, `allPublicMethods`, `allDeclaredMethods`, `allPublicFields`, `allDeclaredFields`, `allPublicClasses`, and `allDeclaredClasses` attributes can be used to automatically include an entire set of members of a class.

Expand All @@ -125,6 +126,28 @@ Code may also write non-static final fields like `String.value` in this example,
More than one configuration can be used by specifying multiple paths for `ReflectionConfigurationFiles` and separating them with `,`.
Also, `-H:ReflectionConfigurationResources` can be specified to load one or several configuration files from the native image build's class path, such as from a JAR file.

### Conditional Configuration

With conditional configuraiton, a class configuration entry is applied only if a provided `condition` is satisfied. The only currently supported condition is `typeReachable`, which enables the configuration entry if the specified type is reachable through other code. For example, to support reflective access to `sun.misc.Unsafe.theUnsafe` only when `io.netty.util.internal.PlatformDependent0` is reachable, the configuration should look like:

```json
{
"condition" : { "typeReachable" : "io.netty.util.internal.PlatformDependent0" },
"name" : "sun.misc.Unsafe",
"fields" : [
{ "name" : "theUnsafe" }
]
}
```

Conditional configuration is the *preferred* way to specify reflection configuration: if code doing a reflective access is not reachable, it is unnecessary to include its corresponding reflection entry. The consistent usage of `condition` results in *smaller binaries* and *better build times* as the image builder can selectively include reflectively accessed code.

If a `condition` is omitted, the element is always included. When the same `condition` is used for two distinct elements in two configuration entries, both elements will be included when the condition is satisfied. When a configuration entry should be enabled if one of several types are reachable, it is necessary to add two configuration entries: one entry for each condition.

When used with [assisted configuration](BuildConfiguration.md#assisted-configuration-of-native-image-builds), conditional entries of existing configuration will not be fused with agent-collected entries as agent-collected entries.

### Configuration with Features

Alternatively, a custom `Feature` implementation can register program elements before and during the analysis phase of the native image build using the `RuntimeReflection` class. For example:
```java
class RuntimeReflectionRegistrationFeature implements Feature {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.Platforms;
import org.graalvm.nativeimage.impl.ConfigurationCondition;
import org.graalvm.nativeimage.impl.RuntimeReflectionSupport;

//Checkstyle: allow reflection
Expand All @@ -68,7 +69,7 @@ public final class RuntimeReflection {
* @since 19.0
*/
public static void register(Class<?>... classes) {
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(classes);
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(ConfigurationCondition.objectReachable(), classes);
}

/**
Expand All @@ -79,7 +80,7 @@ public static void register(Class<?>... classes) {
* @since 19.0
*/
public static void register(Executable... methods) {
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(methods);
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(ConfigurationCondition.objectReachable(), methods);
}

/**
Expand All @@ -90,7 +91,7 @@ public static void register(Executable... methods) {
* @since 19.0
*/
public static void register(Field... fields) {
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(false, fields);
ImageSingletons.lookup(RuntimeReflectionSupport.class).register(ConfigurationCondition.objectReachable(), false, fields);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.Platforms;
import org.graalvm.nativeimage.impl.ConfigurationCondition;
import org.graalvm.nativeimage.impl.RuntimeSerializationSupport;

/**
Expand All @@ -60,7 +61,7 @@ public final class RuntimeSerialization {
* @since 21.3
*/
public static void register(Class<?>... classes) {
ImageSingletons.lookup(RuntimeSerializationSupport.class).register(classes);
ImageSingletons.lookup(RuntimeSerializationSupport.class).register(ConfigurationCondition.objectReachable(), classes);
}

/**
Expand All @@ -75,7 +76,7 @@ public static void register(Class<?>... classes) {
* @since 21.3
*/
public static void registerWithTargetConstructorClass(Class<?> clazz, Class<?> customTargetConstructorClazz) {
ImageSingletons.lookup(RuntimeSerializationSupport.class).registerWithTargetConstructorClass(clazz, customTargetConstructorClazz);
ImageSingletons.lookup(RuntimeSerializationSupport.class).registerWithTargetConstructorClass(ConfigurationCondition.objectReachable(), clazz, customTargetConstructorClazz);
}

private RuntimeSerialization() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.graalvm.nativeimage.impl;

import java.util.Objects;

public final class ConfigurationCondition implements Comparable<ConfigurationCondition> {
private final String typeName;
private static final ConfigurationCondition OBJECT_REACHABLE = new ConfigurationCondition(Object.class.getTypeName());

public static ConfigurationCondition objectReachable() {
return OBJECT_REACHABLE;
}

public static ConfigurationCondition create(String typeReachability) {
Objects.requireNonNull(typeReachability);
if (OBJECT_REACHABLE.typeName.equals(typeReachability)) {
return OBJECT_REACHABLE;
}
return new ConfigurationCondition(typeReachability);
}

private ConfigurationCondition(String typeName) {
this.typeName = typeName;
}

public String getTypeName() {
return typeName;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConfigurationCondition condition = (ConfigurationCondition) o;
return Objects.equals(typeName, condition.typeName);
}

@Override
public int hashCode() {
return Objects.hash(typeName);
}

@Override
public int compareTo(ConfigurationCondition o) {
return this.typeName.compareTo(o.typeName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@
import java.lang.reflect.Field;

public interface ReflectionRegistry {
void register(Class<?>... classes);
void register(ConfigurationCondition condition, Class<?>... classes);

void register(Executable... methods);
void register(ConfigurationCondition condition, Executable... methods);

void register(boolean finalIsWritable, Field... fields);
void register(ConfigurationCondition condition, boolean finalIsWritable, Field... fields);

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@

public interface RuntimeSerializationSupport {

void register(Class<?>... classes);
void register(ConfigurationCondition condition, Class<?>... classes);

void registerWithTargetConstructorClass(Class<?> clazz, Class<?> customTargetConstructorClazz);
void registerWithTargetConstructorClass(ConfigurationCondition condition, Class<?> clazz, Class<?> customTargetConstructorClazz);

void registerWithTargetConstructorClass(ConfigurationCondition condition, String className, String customTargetConstructorClassName);

void registerWithTargetConstructorClass(String className, String customTargetConstructorClassName);
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.function.Function;
import java.util.function.Predicate;

import org.graalvm.nativeimage.impl.ConfigurationCondition;
import org.junit.Assert;
import org.junit.Test;

Expand Down Expand Up @@ -145,8 +146,8 @@ private static void doTestTypeConfig(TypeConfiguration typeConfig) {
}

private static void doTestExpectedMissingTypes(TypeConfiguration typeConfig) {
Assert.assertNull(typeConfig.get("FlagTestA"));
Assert.assertNull(typeConfig.get("FlagTestB"));
Assert.assertNull(typeConfig.get(ConfigurationCondition.objectReachable(), "FlagTestA"));
Assert.assertNull(typeConfig.get(ConfigurationCondition.objectReachable(), "FlagTestB"));
}

private static void doTestTypeFlags(TypeConfiguration typeConfig) {
Expand Down Expand Up @@ -194,12 +195,13 @@ private static void doTestResourceConfig(ResourceConfiguration resourceConfig) {
}

private static void doTestSerializationConfig(SerializationConfiguration serializationConfig) {
Assert.assertFalse(serializationConfig.contains("seenType", null));
Assert.assertTrue(serializationConfig.contains("unseenType", null));
ConfigurationCondition condition = ConfigurationCondition.objectReachable();
Assert.assertFalse(serializationConfig.contains(condition, "seenType", null));
Assert.assertTrue(serializationConfig.contains(condition, "unseenType", null));
}

private static ConfigurationType getConfigTypeOrFail(TypeConfiguration typeConfig, String typeName) {
ConfigurationType type = typeConfig.get(typeName);
ConfigurationType type = typeConfig.get(ConfigurationCondition.objectReachable(), typeName);
Assert.assertNotNull(type);
return type;
}
Expand Down Expand Up @@ -259,11 +261,11 @@ Map<ConfigurationMethod, ConfigurationMemberKind> getMethodsMap(ConfigurationMem
}

void populateConfig() {
ConfigurationType oldType = new ConfigurationType(getTypeName());
ConfigurationType oldType = new ConfigurationType(ConfigurationCondition.objectReachable(), getTypeName());
setFlags(oldType);
previousConfig.add(oldType);

ConfigurationType newType = new ConfigurationType(getTypeName());
ConfigurationType newType = new ConfigurationType(ConfigurationCondition.objectReachable(), getTypeName());
for (Map.Entry<ConfigurationMethod, ConfigurationMemberKind> methodEntry : methodsThatMustExist.entrySet()) {
newType.addMethod(methodEntry.getKey().getName(), methodEntry.getKey().getInternalSignature(), methodEntry.getValue());
}
Expand Down Expand Up @@ -294,7 +296,7 @@ String getTypeName() {

void doTest() {
String name = getTypeName();
ConfigurationType configurationType = currentConfig.get(name);
ConfigurationType configurationType = currentConfig.get(ConfigurationCondition.objectReachable(), name);
if (methodsThatMustExist.size() == 0) {
Assert.assertNull("Generated configuration type " + name + " exists. Expected it to be cleared as it is empty.", configurationType);
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2021, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.configure.config;

import static com.oracle.svm.core.configure.ConfigurationParser.CONDITIONAL_KEY;
import static com.oracle.svm.core.configure.ConfigurationParser.TYPE_REACHABLE_KEY;

import java.io.IOException;

import org.graalvm.nativeimage.impl.ConfigurationCondition;

import com.oracle.svm.configure.json.JsonWriter;

final class ConfigurationConditionPrintable {
static void printConditionAttribute(ConfigurationCondition condition, JsonWriter writer) throws IOException {
if (!condition.equals(ConfigurationCondition.objectReachable())) {
writer.quote(CONDITIONAL_KEY).append(":{");
writer.quote(TYPE_REACHABLE_KEY).append(':').quote(condition.getTypeName());
writer.append("},").newline();
}
}
}
Loading