0

following

public class Testclass {

    private static final LogExtension log = new LogExtension(Testclass.class);

}

should work with just:

@LogExtension
public class Testclass{}

similar to @Slf4j with its annotation it creates an object like in all the classes where it is used.

private static final org.slf4j.Logger internalLog = org.slf4j.LoggerFactory.getLogger(LogExtension.class);

any help will be much appreciated.. thanks for reading. couldn't find much on the internet about how to do it.

I'm trying to create a annotation like

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@interface LogExt{ 
    LogExtension log() default new LogExtension(); 
}

but how to get the class type as default to create object of LogExtension ? to make it work like :

    private static final LogExtension log = new LogExtension(Testclass.class);

Scenario: I'm trying to have a Logger class that can replace SLF4j as per my problem so it Like I want to create a custom annotation like @LogExtension similar to @slf4j which can execute on compile-time to produce

Optimus Prime
  • 69
  • 2
  • 13
  • 1
    What is the reason for you wanting to do this? – Thorbjørn Ravn Andersen Dec 28 '21 at 07:15
  • @ThorbjørnRavnAndersen I want this class to be used by everyone, basically, they should be able to use it just by replacing `@Slf4j` with `@LogExtension` just that. – Optimus Prime Dec 28 '21 at 07:19
  • But why not just keep @slf4j? – Thorbjørn Ravn Andersen Dec 28 '21 at 07:31
  • @ThorbjørnRavnAndersen, `LogExtension` is kind of a class that processes logs from only a few classes. I cant make it an appender coz I don't want all the logs over there. so I'm trying to solve this with the above approach. – Optimus Prime Dec 28 '21 at 07:35
  • Then first do a "how do I write an annotation processor" tutorial or two, and then have a very close look at how the @slf4j annotation does its job. Any reason you just don't want to write the line out by hand yourself? – Thorbjørn Ravn Andersen Dec 28 '21 at 08:36
  • @ThorbjørnRavnAndersen `new LogExtension(Testclass.class);` basically how to get the class automatically in arguments, couldn't understand how slf4j is doing that. – Optimus Prime Dec 28 '21 at 08:41
  • You have the source. Have a closer look. – Thorbjørn Ravn Andersen Dec 28 '21 at 09:15
  • @ThorbjørnRavnAndersen maybe I'm not getting your point .. what I found is `@Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Slf4j { /** @return The category of the constructed Logger. By default, it will use the type where the annotation is placed. */ String topic() default ""; }` and how I'm creating is `@Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @interface LogExt{ LogExtension log() default new LogExtension(); }` not sure how to pass the argument here with the class name where the annotation is used. – Optimus Prime Dec 28 '21 at 09:21

0 Answers0