Android annotations with action - java

Hi i try to create new annotation with action:
My annotation
#Retention(RetentionPolicy.RUNTIME)
public #interface myCustomAnnotations{
String errorMessage();
}
My fucntion
#myCustomAnnotations(errorMessage = "error message")
public void sendIssue() {
}
now i want to log the error message if someone call this method
I search for ever for solution, so if you can help me, it will be awesome!!!

If you don't want to use any existed solutions for logging you can take a look at AspectJ.
With AspectJ you will be able to write an aspect which will be called after, before or around methods specified by your annotation. There are a lot of details, so it's better to see here for example http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html

This won't be done simply by declaring custom annotation on methods. Annotations won't trigger automatically. If it were normal annotations then it could be triggered/executed by Annotation Processor at compile time. In your case, as you're using #Retention(RetentionPolicy.RUNTIME) that means annotation needs to be parsed at runtime manually. Have a good read on this answer. Using the reflection, this is the way you can log your message.

Related

Is it possible to create necessary / required interfaces?

i have a little kont in my brain about structuring our code. We have a REST Backend based on SpringBoot. To handle requests regarding to security checks we use HandlerInterceptors. In some specific cases we need a specific interceptor and not our default one. The default one is registered in a 3rd party lib that no one can forget it. But i want all coders to think about this specific interceptor.
Actually, i just said it to them to achieve this.
Here's my question: Is there an option to create required (or necessary) interfaces which must be implemented? This would be a way to provide our security code by lib and to have the security that every coder implemented our specific interface (also if he just does nothing with it).
pseudo code:
public interface thinkForIt(){
Object SecBean specificSecBean;
public void methodToThinkOn();
}
public SecImpl implements thinkForIt(){
#Override
public void methodToThinkOn(){
return null; // i thought about it but i do not need to do anyting!
}
If the interface thinkForIt would have any annotations like #required, users could get warning or error if they did not implement it...
Looking for a solution and thanks for your comments in advance!
Your overall design is questionable; you are reinventing security code, which is always a red flag. Use Spring Security instead.
However, there's a simple way to ensure that "some bean of type Foo" has been registered with the context:
#Component
#RequiredArgsConstructor
public class ContextConfigurationVerifier {
final Foo required;
}

Creating and using annotation in java

I am reviewing open source spring projects. I am confused about the use of annotations around here. I want to ask to clarify this.
#Target(ElementType.METHOD)
#Retention(RUNTIME)
#Bean
public #interface Merge {
#AliasFor("targetRef")
String value() default "";
#AliasFor("value")
String targetRef() default "";
Placement placement() default Placement.APPEND;
int position() default 0;
Class<MergeBeanStatusProvider> statusProvider() default MergeBeanStatusProvider.class;
boolean early() default false;
}
An annotation has been created here named Merge. It has different parameters and default values.
#Configuration
public class LocalConfiguration {
#Merge(targetRef = "mergedList", early = true)
public List<String> blLocalMerge() {
return Arrays.asList("local-config1", "local-config2");
}
}
And this is usage of #Merge annotation in any class I choosed randomly.
When I examined the code, I could not find any class related to the implementation of Merge annotation. By the way, this problem I'm having isn't just about this annotation. Almost all the annotations I have examined are used without being implemented in any way.
I think I will understand the others if we start from this annotation.
What does this anotation do? What kind of message does it give to the place where it is used. How does the application understand what that annotation does in runtime without being implemented anywhere.
Thanks.
Annotations don't have implementations. They are processed by external classes or tools depending on the RetentionPolicy. In this case, the Merge annotation has Runtime retention so it will be available via reflection once the class is loaded. At runtime any interested party (in this case I assume the Spring Framework) can use getAnnotations on your LocalConfiguration class to detect the Merge annotation and take whatever action that needs to be taken. The possibilities are really up to the framework that defined the annotation. A lot of Spring injection works like this with annotations but they are also used by many other frameworks such as Hibernate, Jersey, etc. The main idea is that annotations act as markers on specific code points to be used by an external entity at a later point.

Create annotation that includes FindBugs' and Lombok's #NonNull

I would like to use Lombok's #NonNull annotation to generate the null-checking code automatically for method parameters while also using FindBugs' #NonNull to use static analysis tools and generate appropriate warnings whenver the case applies.
As of now, I need to do the following:
public void doSomething (#lombok.NonNull #edu.umd.cs.findbugs.annotations.NonNull Object parameter)
{
// Do something
}
This is quite ugly, so I would like to avoid using this syntax. I read about nested annotations (here and here), but I can't seem to find a way to create my own custom annotation with both NonNull annotations as nested annotations. Am I trying to do something that cannot work?
Here's my latest attempt:
#Documented
#Retention (RetentionPolicy.CLASS)
#Target (value={ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
public #interface MyNonNull
{
public lombok.NonNull lombokNonNull () default #lombok.NonNull;
public edu.umd.cs.findbugs.annotations.NonNull findBugsNonNull () default #edu.umd.cs.findbugs.annotations.NonNull;
}
You cannot "merge" annotations with custom annotations, however you can use #ParametersAreNonnullByDefault on the class scope, which should allow edu.umd.cs.findbugs.annotations.NonNull to be inferred.
I think neither of your links will help you. You would need to extend from both with your custom annotation, yet you cannot even extend from one, as all annotations have an implicit extends clause for Annotation.

Problems searching for annotated classes using Reflections API

I'm having a very difficult time using the Reflections API to find classes that are annotated with a custom annotation at runtime. The ultimate goal is to find all classes in the project that are annotated with my custom #Job annotation, collect them, and allow each of them to be run from one location without adding each one to the page manually. However, I'm finding it extremely difficult to get the initial search to work correctly, so I cannot move on with my project.
My current approach is to use:
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("jobs"))
.setScanners(new TypeAnnotationsScanner())
.filterInputsBy(new FilterBuilder().includePackage("jobs")));
Set<Class<?>> jobs = reflections.getTypesAnnotatedWith(Job.class);
where "jobs" is the package containing all of the job classes that I am searching for, which will be annotated with the custom #Job annotation. "jobs" is a base package in my project, but the overall url on my machine looks something like ".../(project)/app/jobs". This setup results in one url being searched, which is ".../(project)/app/" with the additional filter "+jobs.*" in the configuration object. This seems like it is working correctly, but clearly something is wrong because I do not get any classes in the set.
If it matters, the annotation is coded as:
package jobs;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface Job {
String description();
}
The annotation class is located within the same "jobs" package as the job classes I am searching for. An example of a job definition with the annotation included is:
package jobs;
#Job(description = "Description of what the job will do")
public class ExampleJob extends MasterJob {...}
I cannot find what I need to change in order to get this search to function as intended. Thanks for the help, and please let me know if I can clarify anything further.
EDIT: I believe the problem is associated with how the Play Framework loads its classes. Fortunately, the framework provides its own annotation search function, which I used instead. According to a comment, the code I have listed here will work, given that you have all the dependencies to run it. Feel free to use it as a template and let me know if it works for you as well.

how can i trigger my custom annotation when method called?

I want to write my own Secure module library for web but i not solution somethings. Example; I have a class and have a method. Method have my custom annotation.
class example{
#Admin
public void go(){
syso("working");
}
}
When This method called , how can i trigger my annotation.
(Example; Hibernate Validators. We write hibernate annotation on method , it working only method called)
by the way my english is bad :)
Annotations are not "triggered"... you have to write code that looks for their presence and takes action.
The "code" can either be executed at runtime, but is more commonly executed at compile time using the Annotation Processing Tool to alter the source to inject extra, typically cross-cutting, code appropriate for the annotation.

Categories