简体   繁体   中英

Can we load only those classes which we have annotated with our custom annotation?

I came across one question regarding custom annotation. Question :- Suppose we have created a custom annotation, and we applied it to some classes(Suppose in our application/module we have total of 10 classes, and we have applied custom annotation only on 5 classes, rest 5 are annotated with normal inbuilt annotation like @Autowiring, @COmponent and many more) in our app.

Now, when I load the whole application, will it be possible to load or we can say instantiate only those classes which I have annotated with my custom annotation.

Will it be possible?

Assuming

@MyAnnotation
public class MyClass {
   ...
}

Then

if (MyClass.class.isAnnotationPresent(MyAnnotation.class)) {
   MyClass myObj = MyClass.newInstance();
}

Will conditionally instantiate an annotated class.

using entryClass.getAnnotation() we can load the class which we custom annotated. String jarFile = "path/to/jarfile.jar"; DexClassLoader classLoader = new DexClassLoader( jarFile, "/tmp", null, getClass().getClassLoader()); Class<?> myClass = classLoader.loadClass("MyClass");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM