Skip to content

Commit

Permalink
[Java.Interop] use Type.GetType() to find MarshalMemberBuilder (#…
Browse files Browse the repository at this point in the history
…1193)

Context: #1184 (comment)

Previously we were using `Assembly.Load()` and `Assembly.GetType()`,
which require us to ignore various trimmer warnings.

During code review, @vitek-karas asked:

> Is there a reason
> [`JniRuntime.JniMarshalMemberBuilder.SetMarshalMemberBuilder()`]
> can't use
> `Type.GetType("Java.Interop.MarshalMemberBuilder, Java.Interop.Export")`.
> That is something both trimmer and AOT understand and will handle
> without warnings and correctly preserve the .ctor in the call to
> `Activator.CreateInstance`.

Indeed, there isn't a reason to avoid `Type.GetType()` in
`JniRuntime.JniMarshalMemberBuilder.SetMarshalMemberBuilder()`.

If we use `Type.GetType()` with a constant string instead, the
trimmer knows how to handle this properly.
(The code is also simpler.)
  • Loading branch information
jonathanpeppers authored Feb 15, 2024
1 parent 7d1e705 commit c6e3893
Showing 1 changed file with 1 addition and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,7 @@ public JniMarshalMemberBuilder MarshalMemberBuilder {
}
}

[System.Diagnostics.CodeAnalysis.SuppressMessage ("Design", "CA1031:Do not catch general exception types", Justification = "the *.Export assemblies are optional, so we don't care when they cannot be loaded (they are presumably missing)")]
#if NET
[DynamicDependency (DynamicallyAccessedMemberTypes.PublicParameterlessConstructor, "Java.Interop.MarshalMemberBuilder", "Java.Interop.Export")]
[UnconditionalSuppressMessage ("Trimming", "IL2026", Justification = "DynamicDependency should preserve the constructor.")]
[UnconditionalSuppressMessage ("Trimming", "IL2072", Justification = "DynamicDependency should preserve the constructor.")]
[UnconditionalSuppressMessage ("Trimming", "IL2035", Justification = "Java.Interop.Export.dll is not always present.")]
#endif
partial void SetMarshalMemberBuilder (CreationOptions options)
{
if (!options.UseMarshalMemberBuilder) {
Expand All @@ -45,14 +39,7 @@ partial void SetMarshalMemberBuilder (CreationOptions options)
return;
}

Assembly jie;
try {
jie = Assembly.Load (new AssemblyName ("Java.Interop.Export"));
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine ($"Java.Interop.Export assembly was not loaded: {e}");
return;
}
var t = jie.GetType ("Java.Interop.MarshalMemberBuilder");
var t = Type.GetType ("Java.Interop.MarshalMemberBuilder, Java.Interop.Export", throwOnError: false);
if (t == null)
throw new InvalidOperationException ("Could not find Java.Interop.MarshalMemberBuilder from Java.Interop.Export.dll!");
var b = (JniMarshalMemberBuilder) Activator.CreateInstance (t)!;
Expand Down

0 comments on commit c6e3893

Please sign in to comment.