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 :)
7
u/xRageNugget Jul 06 '22
That sounds like string format with extra steps!
1
u/chinmay06 Jul 06 '22
Yes brother it is but i am trying to explore is there any direct way we can implement it in our environment so that we don't have to call it multiple times.
6
u/Fletsky Jul 06 '22
I never used fstring in python, so I didn't know how it work. But after reading your code, documentation and examples, I still don't have any idea how it is supposed to work. Is that some statefull String formatter? How is it used in python?
About code I have one advice. It is not a good idea to catch all exceptions and just print stack trace. It would be better to leave exception handling to user, so he can catch those exceptions himself and decide what he wants to do with it.
2
u/chinmay06 Jul 06 '22
Yes about the exception you are right ! But as mentioned on the page I am learning java and new to java I have worked in python though
In python you only write print(f"Your message {yourvariable}") for printing or even for any type of string a=f"{declaredVariable}"
in java as you know we have to use .format or printf with variable substitution ;_ which atleast i feel hectic as i have come on java from python ;)
2
u/loomynartylenny Jul 06 '22
I never used fstring in python, so I didn't know how it work.
Well, this explains Python's fstrings, if that's of any interest to you: https://peps.python.org/pep-0498/
2
u/chinmay06 Jul 06 '22
If anyone can help me integrate the code directly in java then it would be great help instead of instancing it multiple times through all classes
6
u/8igg7e5 Jul 06 '22
They're already considering something richer than this with String Templates.
It even has a work-in-progress branch in the jdk and a fair bit of discussion on the JDK dev lists (Project Amber).
2
u/chinmay06 Jul 06 '22
Thanks for your reply ! I have check the above String Templates that is for open JdK right ? I am using Java 1.8 Oracle and trying to create a program which will be similar to F strings in python above string Templates needs to specify the backslash as escape characters ;_
2
u/8igg7e5 Jul 06 '22
Note that the Oracle JDK is now just a build of OpenJDK.
Jave 8 is now quite old (2014), with two LTS releases since then (11 and 17), the current release being 18 (and the next due in September, every 6 months).
While a lot of older projects still use JDK8 (and will likely continue to do so, as there are some challenges to migration past Java 9), newer projects (and those that were able to upgrade) have moved on. Some major frameworks are moving to Java 17 as the minimum.
Each Java release is a specification, and features/changes (other than fixes) are almost never added once released - so 'integrating into Java 8' won't happen, and clearly String Templates would be a much richer alternative in the future anyway.
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...
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
2
u/istarian Jul 06 '22
You might want to use regex patten matching for getFString method. That way you can just match on something like [a-zA-Z]* for alphabetic characters.
It’s also relatively easy to use String.replace(…)
1
u/istarian Jul 06 '22 edited Jul 06 '22
https://dzone.com/articles/java-string-formatting
https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
If you want to convert a class instance to a String, then implement/use the toString method.
•
u/AutoModerator Jul 06 '22
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full - best also formatted as code block
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.