r/learnjava • u/chinmay06 • 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 :)
2
Upvotes
r/learnjava • u/chinmay06 • Jul 06 '22
Hello Everyone,
I Have created F string for java using reflection api.
Kindly check the below utility.
All contributions will help.
Thanks :)
2
u/8igg7e5 Jul 07 '22
Things you probably need to take into account.
fields are typically private
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).
You'll want to support escaping the
{...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
fprintto befprint(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).Due to reflection costs, you should probably use a static factory method to acquire a formatter (
FStringis 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.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...
Then printing the following...
With the static method (statically imported)...
vs
FString(using my proposed extension to capture multiple sources, including simple variables)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"