Skip to content

Commit

Permalink
fallback to getDeclaredConstructor after trying getConstructor
Browse files Browse the repository at this point in the history
  • Loading branch information
eiennohito committed Jun 23, 2023
1 parent 8ae840a commit 24959b5
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions src/main/java/com/worksap/nlp/sudachi/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -223,22 +223,28 @@ public static Config fromClasspathMerged(String name) throws IOException {
}

/**
* Create Config object from the passed resource. Resources are created by {@link PathAnchor}.
* Create Config object from the passed resource. Resources are created by
* {@link PathAnchor}.
*
* @param resource resource object capturing
* @param anchor object that will be used for path resolution and class loading
* @param resource
* resource object capturing
* @param anchor
* object that will be used for path resolution and class loading
* @return parsed Config object
* @param <T> can be anything
* @throws IOException when IO fails
* @throws FileNotFoundException if resource can not be found
* @param <T>
* can be anything
* @throws IOException
* when IO fails
* @throws FileNotFoundException
* if resource can not be found
* @see PathAnchor#resource(String)
*/
public static <T> Config fromResource(Resource<T> resource, PathAnchor anchor) throws IOException {
if (resource instanceof Resource.Classpath) {
return fromClasspath((URL)resource.repr(), anchor);
return fromClasspath((URL) resource.repr(), anchor);
}
if (resource instanceof Resource.Filesystem) {
return fromFile((Path)resource.repr(), anchor);
return fromFile((Path) resource.repr(), anchor);
}
if (resource instanceof Resource.Ready) {
Object ready = resource.repr();
Expand Down Expand Up @@ -726,7 +732,7 @@ public T instantiate(PathAnchor anchor) {

T result;
try {
Constructor<? extends T> constructor = clz.getConstructor();
Constructor<? extends T> constructor = lookupConstructor(clz);
result = constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException e) {
Expand All @@ -738,6 +744,19 @@ public T instantiate(PathAnchor anchor) {
return result;
}

private Constructor<? extends T> lookupConstructor(Class<? extends T> clz) throws NoSuchMethodException {
try {
return clz.getConstructor();
} catch (NoSuchMethodException ignored) {
try {
return clz.getDeclaredConstructor();
} catch (NoSuchMethodException | SecurityException ignored2) {
throw new NoSuchElementException("class " + clz
+ " did not have accessible no-arg constructor or security policy forbids access");
}
}
}

/**
* Add a string value to the plugin configuration
*
Expand Down

0 comments on commit 24959b5

Please sign in to comment.