Giter VIP home page Giter VIP logo

classindex's People

Contributors

cpiotr avatar igor-makarov avatar jdhoek avatar ptahchiev avatar sentinelt avatar thjaeckle avatar tomekpiotrowski avatar xitep avatar yannic92 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

classindex's Issues

Removing dependency to jaxb-api

As far as I see the only reason for the jaxb-api dependency is that it is used in a JavaDoc comment.
Wouldn't it be better to exclude this from dependencies?
It doesn't seem to be worth adding a dependency just to mention it in a JavaDoc comment.

It might be possible that I just didn't see where you're actually using this dependency.

External indexing settings

Currently, it is only possible to index classes based on their annotated superclass or meta-annotated annotation. To do so, those "markers" must not belong to foreign lib or java classlib - and due to this limitation it is impossible to find, say, all Serializable classes in your project with ClassIndex.
Some way of external configuration is required to fix this.

ClassIndex must check for NoClassDefFoundError also

At the moment the ClassIndex is only checking for a ClassNotFoundException during class loading:
https://github.com/atteo/classindex/blob/master/classindex/src/main/java/org/atteo/classindex/ClassIndex.java#L404-L406

However, I believe it should be checking also for NoClassDefFoundError (see image):
noclassdeffound

I have a maven project with two modules:

  • moduleA
  • moduleB defines module A as optional dependency.

Then the client has the option to chose which combination of modules to add in their classpath - moduleA, moduleB, both modules or none of the modules.

If the customer selects moduleB only then I try to find subclasses:

ClassFilter.only().topLevel().from(ClassIndex.getSubclasses(AbstractEntityDefinition.class))

and then it fails with NoClassDefFoundError because the index file in moduleB was created when moduleA was there during compile time but is missing at runtime now.

Deprecated Gradle setup

Since Gradle 4.x, there are new recommendations for dependencies.

Compile is deprecated

Configuration 'compile' is obsolete and has been replaced with 'implementation'

Annotation processor is deprecated

Execution failed for task ':app:javaPreCompileDebug'.
Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor. Please add them to the annotationProcessor configuration.
- jetified-classindex-3.4.jar (org.atteo.classindex:classindex:3.4)
Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior. Note that this option is deprecated and will be removed in the future.
See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.

No index file is generated after compile

I have added classindex 3.4 as a maven dependency. The jar is included in the project classpath.

I'm using the @IndexSubclasses annotation on a class but after i compile no index file is generated.
Does this work or am I missing a step?

I would appreciate some help!

Indexing methods too?

Is it possible to process annotations and javadocs on methods as well as on types/classes?

Incremental compilation using Gradle is disabled

In my Gradle log, I noticed that it needs to perform a full recompilation for some of the subprojects because of ClassIndexProcessor usage.

> Task :compileJava
Created classpath snapshot for incremental compilation in 0.049 secs.
Class dependency analysis for incremental compilation took 0.257 secs.
Full recompilation is required because org.atteo.classindex.processor.ClassIndexProcessor is not incremental. Analysis took 0.359 secs.

The message looks odd to me because I thought the annotation would work with incremental compilation. I looked at the Gradle documentation for marking annotation processors as incremental and couldn't find META-INF/gradle/incremental.annotation.processors in the published jar for classindex.

https://docs.gradle.org/4.10.3/userguide/java_plugin.html#sec:incremental_annotation_processing

Maybe I'm missing something? Or is this not supposed to work? Thanks

Gradle version: 4.10.3
JDK 8
classindex version: "org.atteo.classindex:classindex:3.4"

META-INF is not changed when file is removed

I use @IndexSubclasses on the interface ExtensionIF.
I created a file Ext1 that subclasses ExtensionIF.
I created a file Ext2 that subclasses ExtensionIF.

The method ClassIndex.getSubclasses(ExtensionIF.class) returns Ext1 and Ext2. This is good!
The method ServiceLoader.load(ExtensionIF.class) returns Ext1@1 and Ext2@2. This is good!

I now remove Ext2.

The method ClassIndex.getSubclasses(ExtensionIF.class) returns Ext1. This is good!
The method ServiceLoader.load(ExtensionIF.class) exits with an exception:
Exception in thread "main" java.util.ServiceConfigurationError: gti.extension.ExtensionIF: Provider gti.extension.Ext2 not found
at java.util.ServiceLoader.fail(ServiceLoader.java:239)
at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
at Test.main(Test.java:17)

It seems that the file META-INF/services/gti.extension.ExtensionIF is not changed when I remove
a file. Is this is a bug? Is it fixable?

Can't write index file...

I receive an error

Can't write index file: Attempt to reopen a file for path .....\META-INF\services\com.cf.model.Builder

I am using maven 3.2.1, JRE 1.8.0_25

The java class source files being processed are generated by another processor and implement an interface that I have annotated with @IndexSubclasses. These source files exist in two packages.

Regards

Not working with Eclipse?

I created a new Java project in Eclipse, added the evo and guava jars, followed the example in the "Usage", but I don't see any index file being generated and it doesn't print out what it's supposed to print out.

What am I missing?

Using evo-classindex-1.3.jar and guava-14.0.1.jar

It only print out the first line, not the others:

  System.out.println("!!!! Hello");
  for(final Class<?> klass : ClassIndex.getAnnotated(Entity.class))
     {
     System.out.println("!!!! " + klass.getName());
     }

Eclipse Juno on a Mac

Adding custom ClassIndexProcessor breaks Maven build

In a Maven project, ClassIndex works when I annotate the scanned annotations with @IndexAnnotated. But when I try implementing a custom ClassIndexProcessor, the compiled java classes seem to be missing from the build as soon as I build the project with my custom processor listed in META-INF/services/javax.annotation.processing.Processor.

I have created a bare bones minimal working example of the problem I am seeing:

https://github.com/LableOrg/classindex-compilation-issue

In this example, if I comment out my class in META-INF/services/javax.annotation.processing.Processor, the project builds, and can be run:

mvn clean install
mvn exec:java

Of course, no classes are found by ClassIndex, because the annotation it is looking for is not annotated with @IndexAnnotated.

Now if I run this example project as-is, leaving my custom class in the services file, the compiled Java classes end up missing in the target directory.

Is this a bug in ClassIndex, or am I using it wrong? Can you reproduce this issue with my example?

Is it intended not to index anon classes?

Consider the following example

@IndexSubclasses
public interface I { /* ... */ }

public interface J extends I { /* ... */ }

public class SomeClass
{
   public static final J j = new J() { /* ... */ }; // Anon implementation of J.
}

I would expect that the anon class (which compiles to a class file name SomeClass$1, disregarding the package name) would be included in the index of the interface I. However, a test showed that this is not the case, which brings me to the question whether this is intended?

jaxb.index file not of the expected format

Hi,

The jaxb.index file produced and consumed by the evo-classindex library is not in the format described in the JAXB documentation at https://jaxb.java.net/nonav/2.2.1/docs/api/javax/xml/bind/JAXBContext.html.

evo-classindex use the fully qualified class name (including the package name) but the specification mandates for the simple class name relative to the package.

Is this on purpose?

This is a concern for me since I would like to use ClassIndex.getPackageClasses(String) with a jaxb.index produced by another tool (maven-jaxb22-plugin).

Regards,
Alain Gilbert

Incremental compilation empties index files

I compiled the project with ant. If the compilation starts from an empty state, then the indexes are correctly generated. After adding a new file, the next compilation will be incremental, i.e. ant only calls javac with the changed file. The result is that the evo-classindex generated file in META-INF is recreated, but it only contains the new class.

For ant the ideal solution would be to check if the index file already exists, and only update it if it is necessary, by appending the missing class names. Deleting classes would still require a clean build, but a simply modification of an existing class would not render the index files useless.

Generics

We use Guice and want to simply annotate our providers to bind them quickly at application startup. This was my first attempt:

@AutoProvider
public class CryptoFactory implements Provider<Crypto> {

    @Override
    public Crypto get() {
        if (Env.isLocal()) {
            return new CryptoFake();
        }

        return new CryptoReal();
    }
}

@IndexAnnotated
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoProvider {
}

This should allow me to remove this manual binding:

bind(Crypto.class).toProvider(CryptoFactory.class);

It sort of works. But because of type erasure I need to get the factory return type Crypto via reflection. Then I duplicated the type information in the annotation:

@AutoProvider(provides = Crypto.class)
public class CryptoFactory implements Provider<Crypto> {

    @Override
    public Crypto get() {
        if (Env.isLocal()) {
            return new CryptoFake();
        }

        return new CryptoReal();
    }
}

@IndexAnnotated
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoProvider {

    Class<?> provides();
}

Now I don't need reflection. BUT there is duplication, since I need to specify Crypto.class twice now. So it would be great if there could be SOME way to access the generic type information.

Indexing test classes

One more issue on eclise jdt integration...

Indexes for test classes appears in /target/classes but not in /target/test-classes (compiled classes are still appear in target/test-classes).

I think it is JDT issue (it calls processor with incorrect preconditions for test classes), but I'm not familiar enough with annotation processors to formulate this issue. Could you please help me to write such issue?

Thanks

Shading relocations are ignored in ClassIndexTransformer

Index files

When annotations annotated with @IndexAnnotated are relocated during shading, the index file created in META-INF/annotations does not reflect the relocated package.

Expected

META-INF
└── annotations
    └── shaded.org.atteo.tobemoved.CustomAnnotation

Actual

META-INF
└── annotations
    └── org.atteo.tobemoved.CustomAnnotation

Index file contents

Index file with classes annotated with annotations using @IndexAnnotated does not reflect relocations.

Expected

cat ./META-INF/annotations/org.atteo.tobemoved.CustomAnnotation
shaded.org.atteo.CustomComponent

Actual

cat ./META-INF/annotations/org.atteo.tobemoved.CustomAnnotation
org.atteo.tobemoved.CustomComponent

Java 9, modulepath and jrt URLs

There's a talk about Java 9 support in all similar libraries. E.g. here's the relevant issue in Reflections, and this library was mentioned.

What's the status on Java 9 support here?

Indexing Annotation- Custom Processor

I have the custom processor included as a jar dependency and when I trying to index based on certain annotation ,zero classes gets indexed, does the custom processor needs to be same project as the other one.

The ClassIndexing and runnable jar

hi ,
I have an issue with your framework, i use 3.3 version, all is working fine from eclipse but when exporting to runnable jar its not working any more (the jar is runnable and working only the mechanism is not) could you please assist on this ?

eco-classindex dependency on guava is overweight

Hi,

evo-classindex could be made more lightweight by removing the dependency on guava since it is used to pull a single constant (UTF-8).

You could use the Apache commons-collections library instead of Google collect package for the handling of collections.

A saving of 1.5mb.

Regards,
Alain Gilbert

@IndexSubclasses

When using @IndexSubclasses with for example 100 sub classes I would like a @IndexIgnore so I can selectively ignore some classes.

This is because I want to share the same interface but not always have evo-classindex find it.

For example I have a base interface A with "@IndexSubclasses"

class B1 B2 and B3 implement A.

class C1 - C100 implement B1 or B2 or B3.

I want to use an annotation to ignore indexing B2 or C5, etc..

Scanning from multiple android modules overwriting index file instead of appending

Hi @sentinelt

Thanks for this great library! Been playing with it for some time but I encountered the following issue on android. Say we had:

App (Android App Target)

-> some annotated classes

MyLib (Android Library Project)

-> some annotated classes

(code that depends on finding annotated classes from both targets with a compile time annotation)

Adding on App's build.gradle & MyLib's build.gradle seems to be overwriting the index file instead of appending.

Currently using for invocation:

    implementation 'org.atteo.classindex:classindex:3.4'
    annotationProcessor 'org.atteo.classindex:classindex:3.4'

in both gradle files, Also tried all permutations (App & not lib, lib & not app, both) seems like the second time the annotationProcessor directive runs the index file that goes in META-INF/annotations only the latest annotated classes persist and make it into the APK.

Is this something I could extend in this library or just not supported in Android? any leads?

Thanks :)

APT build based seems not work

Hello,

I try to make ClasIndex 3.1 work. I add the jar of classIndex (M2_REPO/org/atteo/classindex/classindex/3.1/classindex-3.1.jar) in the factory path.
I created my proper annotation which is Annotated with :


@target(ElementType.TYPE)
@retention(RetentionPolicy.RUNTIME)
@IndexAnnotated
public @interface Definition {}


and annotated a class :


@Definition
public class Message{}


But when I retrieve the annotated classes :


Iterable<Class<?>> annotated = ClassIndex.getAnnotated(Definition.class);


The iterator is empty (hasNext return false). And I don't have a META_INF/annotations folder created at compile time.
Did I miss something ?

Regards

Atha

ClassIndex.getAnnotated returns classes that are no longer annotated

Hi there,
When indexing classes with @IndexAnnotated and removing the annotation again incremental compilation does not seem to update the index correctly so that the class is removed again from the index. I know there were similar issues for classes that were removed causing the indices to become outdated.
Doing a rebuild all fixes the issue.

My proposed solution would be to check for the classes returned by getAnnotated whether the annotation is still present.

Setup:
IntelliJ 2019.2 using the built in compiler

ProGuard

After I enabled ProGuard, method ClassIndex.getAnnotated(myAnnotaion.class) didn't find any class ? I use classindex in android library project.

getAnnotated returns an empty Iterator

I wrote this code :

        System.out.println("Step 1");
        for(Class<?> jclass : ClassIndex.getAnnotated(EventListener.class))
        {
            System.out.println("Step 2");
            // Other random things
        }

The text Step 2 is never outputed. I tried to do this :

        if(ClassIndex.getAnnotated(EventListener.class) == null || !ClassIndex.getAnnotated(EventListener.class).iterator().hasNext()) System.err.println("err");

and it shows err. Here are my other classes :

@EventListener
public class EventHandler
{}

IndexAnnotated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EventListener
{}

(I use Eclipse Luna on Xubuntu and I putted the Eclipse specific setting for the annotation processing thing)

Configuring classindex processor in eclipse

I'm not sure that this issue belongs to evo-classindex, but not to JDT in eclipse IDE.

I used evo-classindex 1.0 and successfully configured annotation processing in the eclipse (added evo-classindex and google-guava libraries).
The only trouble was incremental compilation: when I change a class that should be indexed, the whole index is replaced with index of size 1.

As far as I understand an issue about incremental compiling is resolved in 1.1. Now I've switched to 1.1 (and guava 13.0.1) and got an runtime exception:

Exception thrown by Java annotation processor 
org.atteo.evo.classindex.processor.ClassIndexProcessor@799a1b87
java.lang.RuntimeException: java.io.IOException: org.eclipse.core.internal.resources.ResourceException: Resource '/plugin/target/classes/META-INF/services/ru.Plugin' does not exist.
    at org.atteo.evo.classindex.processor.ClassIndexProcessor.process(ClassIndexProcessor.java:154)

plugin -- is my project, ru.Plugin is an interface annotated with IndexSubclasses.

This exception occurs if the file does not exist and if the file exists. Nevertheless compiling with maven from command line successes.

Thanks.

attach meta info?

Would it be feasible to attach meta information to each class in the index?

Here is our use case:
We have several hundred pages, they all inherit from BasePage.java. There is also a mapping file, PageIndex.java they is basically a big hash map that looks like this:

   .put("/some/path", "com.myproject.pages.XYZ")

The reason we need to use the full qualified name is that we want to prevent the classloading of the page (slow on our platform). So in order to apply classindex to this we'd need to attach the page's path to the index (since we can't load the entire class and evaluate any runtime annotations).

So, basically I'd imagine a annotation like @IndexMeta("/some/path") and the ability to read it from the classindex API.

I know this is quite a big concept, but I just wanted to throw it out there :)

Stephan

Return class names?

Hey,

first let me tell you: we totally love you little library here. It has saved us a lot of trouble. We are hosted on App Engine and every classpath scanning we can avoid makes us very happy :)

We also use classindex to initialize Guice: all injectable classes are annotated with @autoBind and then we simply iterate through all the classes and add them. This has worked quite well for us in the beginning but now we run into problems. We have so many classes to bind that the slowest part of our application startup is now the Guice initialization. The profiler tells us that the classloading is responsible for that (it's especially slow on App Engine).

So what would really help us would be something like this:

public static Iterable<String> getAnnotatedClassNames(Class<? extends Annotation> annotation)

This method could simply return the class names without actually loading them.

Do you think this is something you could add?

No index when annotation is on package-info

I have a package-info.java class that looks like this:

@MixIn @MenuFolder(id = "leasingfolder", weight = 11)
package com.nemesis.platform.module.commerce.core.definition.leasing;

import com.nemesis.platform.core.mixin.MixIn;
import com.nemesis.platform.core.service.annotations.MenuFolder;

Now I want to find all package-info classes that have the MenuFolder annotation. The MenuFolder annotation is indexed:

@Indexed
@Documented
@IndexAnnotated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MenuFolder {
    String id() default "{com.nemesis.menufolder.id}";

    int weight() default 0;
}

However, during compilation I see no index in META-INF/annotations/ is created.

No ouput

Hi,

I'm just trying to get started with evo-classindex but I'm having issues. I added @IndexSubclasses to a class of mine but when I look into the JAR's META-INF there is an empty folder called services. What might have gone wrong?

PS: It's a Gradle-based WAR project.

Problem with eclipse and "Indexing when annotations cannot be used"

I want to find classes with the annotation "javax.persistence.Entity".
This annotation is in the jar "hibernate-jpa.jar"

I've created a Processor as explained in "Indexing when annotations cannot be used".
This works with javac.
But it doesn't work with eclipse. The stacktraces is included below.
The problem is that the Entity.class is not found on the path. I do not know why javac has the hibernate-jpa.jar on its claspath and the eclipsecompiler doesn't.

But this problem can be circumvented if the method indexAnnotations(Class... classes) is changed
to indexAnnotations(String... classNames). The dependency on the external libs dissappear now.
Maybe this method should be added?

Unable to create instance of annotation processor gti.classindex.processor.MesClassIndexProcessor
java.lang.NoClassDefFoundError: javax/persistence/Entity
at gti.classindex.processor.MesClassIndexProcessor.(MesClassIndexProcessor.java:11)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at org.eclipse.jdt.apt.core.internal.ClassServiceFactory.newInstance(ClassServiceFactory.java:26)
at org.eclipse.jdt.internal.apt.pluggable.core.dispatch.IdeAnnotationProcessorManager.discoverNextProcessor(IdeAnnotationProcessorManager.java:93)
at org.eclipse.jdt.internal.compiler.apt.dispatch.RoundDispatcher.round(RoundDispatcher.java:116)
at org.eclipse.jdt.internal.compiler.apt.dispatch.BaseAnnotationProcessorManager.processAnnotations(BaseAnnotationProcessorManager.java:159)
at org.eclipse.jdt.internal.apt.pluggable.core.dispatch.IdeAnnotationProcessorManager.processAnnotations(IdeAnnotationProcessorManager.java:135)
at org.eclipse.jdt.internal.compiler.Compiler.processAnnotations(Compiler.java:933)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:443)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:419)
at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:372)
at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.compile(BatchImageBuilder.java:187)
at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:332)
at org.eclipse.jdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:61)
at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:256)
at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:175)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:735)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:246)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:301)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:304)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:263)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:403)
at org.eclipse.core.internal.resources.Project$1.run(Project.java:566)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2240)
at org.eclipse.core.internal.resources.Project.internalBuild(Project.java:544)
at org.eclipse.core.internal.resources.Project.build(Project.java:112)
at org.eclipse.jdt.internal.ui.util.CoreUtility$BuildJob.run(CoreUtility.java:159)

Android with Gradle

Hi there! Should this just work if I add it to my Android build.gradle? I didn't manage to make it work: getSubclasses doesn't return anything (and yup, I have the right annotation in the parent class). Should it just work on Android, or am I missing something?

Not working in Eclipse 4.4.0?

I've tried adding the classindex jar to the Eclipse annotation processing settings, as suggested.

I've tried adding guava as well.

I've tried with ClassIndex v3.1 and v3.2.

The jaxb.index file is not created, and I can't see any signs of the annotation processor actually being run.

Any suggestions?

POM License settings

Hi, can you add something like this to your POM please:

<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://apache.org/licenses/LICENSE-2.0</url>
<distribution>repo</distribution>
</license>
</licenses>

I'm using org.complykit : license-check-maven-plugin : 0.5.1 and my maven build fails because you didn't specify a license.

[INFO] --[ Licenses found ]------
[INFO] testng: apache-2.0
[INFO] evo-classindex: null
[INFO]
[INFO] RESULT: At least one license could not be verified or appears on your blacklist. Build fails.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Thanks!

Nas.

Add @RegisterService annotation

Usage

@RegisterService(SomeOneElsesInterface.class)
public class MyImplOfSomeOneElsesInterface implements SomeOneElsesInterface {
    ...
}

The annotation (the related annoation processor) adds the MyImplOfSomeOneElsesInterface to the /META-INF/services/com.foo.bar.SomeOneElsesInterface file for the service loader.

The usecase for this annotation is to simplify the registration for the service loader for interfaces, that don't use this library on their own. And thus avoid issues due to renaming classes.

The annotation can probably use RetentionType.SOURCE as it isn't needed at runtime/for other dependencies.

Other name suggestions for the annotation:

  • @RegisterForServiceLoader

Sub interfaces are added to the service list

I have a sub-interface that extends my @IndexSubclasses interface, that class gets added to the META-INF/services file. This causes an exception in the application at runtime.

Classindex: v3.9

java.util.ServiceConfigurationError: com.example.Interface: Provider com.example.SubInterface could not be instantiated
	at java.util.ServiceLoader.fail(ServiceLoader.java:232)
	at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
	at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
	at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
	at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
	at com.example.Registry.init(Registry.java:78)
	... plenty more
Caused by: java.lang.InstantiationException: com.example.SubInterface
	at java.lang.Class.newInstance(Class.java:427)
	at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
	... 73 more
Caused by: java.lang.NoSuchMethodException: com.example.SubInterface.<init>()
	at java.lang.Class.getConstructor0(Class.java:3082)
	at java.lang.Class.newInstance(Class.java:412)
	... 74 more

Test-Sourcen

@IndexSubclasses
public interface IndexedInterface {
}
public interface SubInterface extends IndexedInterface {
}
class IndexTest {

    @Test
    void testGetAll() {
        ServiceLoader.load(IndexedInterface.class)
                .forEach(System.out::println); // <-- Boom
    }

}

`ClassIndex.getAnnotated()` return nothing, but classes with annotation exist.

For example, this code return empty collection for iterating: (for each iterate for zero elements)

ClassIndex.getAnnotated(Configuration::class.java).forEach {
    // ...
}

My configuration annotation:

image

build.gradle:

internal "org.atteo.classindex:classindex:$class_index_version"
annotationProcessor "org.atteo.classindex:classindex:$class_index_version"

note: internal is implementation but also for including library in jar.

In META-INF/services files:

image

Latest library version, JDK 1.8, Kotlin 1.3.71. Used with Minecraft Forge API. Gradle 5.X.X (latest of 5).

FieldIndex?

How about supporting indexing of annotations on fields (e.g. FieldElement as well as TypeElement)? Would you accept a pull request?

i.e.

@IndexAnnotated public @interface MyAnnotation {}

class MyClass {
    @MyAnnotation String myField;
}

Iterable<Field> fields = ClassIndex.getAnnotatedFields(MyAnnotation.class);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.