r/learnjava • • Jul 06 '22

F string For Java

Hello Everyone,

I Have created F string for java using reflection api.

Kindly check the below utility.

All contributions will help.

Thanks :)

https://github.com/chinmay-sawant/FString-For-Java

2 Upvotes

14 comments sorted by

View all comments

2

u/8igg7e5 Jul 07 '22

Things you probably need to take into account.

  1. fields are typically private

  2. Synthetic properties will use getter methods and may not have a field to reference. So you probably need to deal with finding getters based on the Java Bean naming convention (and falling back to the record convention).

  3. You'll want to support escaping the {...

  4. Often printing wants to reference local variables as well, or fields from several objects, but you won't be able to do that here, as local variables aren't visible to reflection and the proposed format can't support multiple sources. You could change fprint to be fprint(String fmt, Object... sources) and the format becoming "Hello There {0.a} {1}" (such that it looks for the 'a' attribute of the 0th source, or prints the source itself if no attribute is given).

  5. Due to reflection costs, you should probably use a static factory method to acquire a formatter (FString is atypical Java naming - as abbreviated type-names are discouraged). The factory will want to cache reflection information for types it's seen before - but probably softly-referenced.

  6. If you're looking to replace String.format you'll probably also want padding / format specifiers.

 l

At the moment it looks like a static util method might be easier to use...

public final class OutputUtil {
    private OutputUtil() {}

    public static void fprintln(String fmt, Object... args) {
        System.out.printf(fmt, args);
        System.out.println();
    }
}

Then printing the following...

Person p = ...
p.setName(...);
int status = ...

With the static method (statically imported)...

fprintln("Hello There %s (%d)", p.getName(), status);

vs FString (using my proposed extension to capture multiple sources, including simple variables)

FString fs = new FString();
fs.fprint("Hello There {0.name} ({1})", p, status);

In the end, I think any suitably rich solution will struggle to be nicer to use than the default Java format strings - until String Templates replace them.

As /u/xRageNugget says, it feels like "string format with extra steps"

1

u/chinmay06 Jul 07 '22

Thank you so much for your response. :)