Home > Software design >  How to get interface method name as String?
How to get interface method name as String?

Time:04-25

I'd like to get an interface method name as String. Here is my code. It's a Spring Batch reader.

  @Bean
  public ItemReader<Data> reader() {
    var sorts = new HashMap<String, Direction>();
    sorts.put("id", Direction.ASC);

    return new RepositoryItemReaderBuilder<Data>()
        .name("dataReader")
        .repository(dataRepository)
        .methodName("myCustomMethod")
        .arguments("latest")
        .sorts(sorts)
        .build();
  }

As you can see I have a dataRepository interface that has a method myCustomMethod. I'm currently using the handwritten String as the methodName method argument. I was wondering if I could somehow get the name as a String via Java, e.g. something like (pseudo code)

        .methodName(dataRepository.myCustomMethod.getName())

That does not work and I'm getting an error.

myCustomMethod cannot be resolved or is not a field

My problem is that the manually entered String is not really save when it comes to refactoring. I could simply remove the myCustomMethod and the compiler would not complain. I'd like to have this safety during compile time.

Any ideas?

CodePudding user response:

You should use introspection/reflection (don't remeber what's the exact word in English). But basically you could do something like this to get all the methods:

IDoable.class.getMethods()

Then you can just iterate over the array and do

method.GetName()

Also, you just need to iterate if needed. But if you, for example, need the name of the 2nd method of an interface, you can simplify this to :

IDoable.class.getMethods()[1].getName()

CodePudding user response:

In case your interface only has 1 method, you could fetch the method name using reflection like:

dataRepository.getClass().getMethods[0].getName()
  • Related