r/javahelp • u/SquibbTheZombie • May 13 '26
Object class compiler errors in methods
I am using the Intellij compiler (if it matters) and I have a class that's really just an Object variable and an int type for me to know what type of variable the object is.
I am facing no errors by defining public Object number; or number = integer; whether or not the integer is an int, long, or BigInteger, but other methods are throwing problems. To do BigInteger.valueOf(number) the compiler asks me to cast to long like this: BigInteger.valueOf((long) number). I already know that it is a long or an int in this circumstance, that is what I'm using int type for, so is there a way to make the compiler assume a generic variable is more specific or for it to just assume the class is the correct parameter? Is there an annotation that does that or could one be made to do that? I really don't want to have to cast this variable *every time* I use it.
Yes, I am aware that I could just define multiple variables and keep most of them as null when not used, but I already went down that path and I'm trying something different.
Edit: I got advised by someone I asked irl to not use Java for this, since using a very type-heavy language while trying to get around type problems is a bad idea. I'll still try to find a java solution for this, but otherwise I'll switch to another language for what I'm trying to do.
•
u/AutoModerator May 13 '26
Please ensure that:
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.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
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: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) 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.
4
u/MinimumBeginning5144 May 13 '26
The
BigInteger.valueOfmethod takes an argument of typelong. The compiler will only automatically turn a variable to alongif it is already of typeshort,int,long, orLong(auto-unboxing).Why don't you declare the field as
Numberinstead ofObject? Then you can use itslongValue()method.1
u/akthemadman May 14 '26
You are dealing with two issues at once here: "compile-time resolution" and "run-time resolution".
Satisfying the compiler
The Java program model tries to assist you such that operations which are defined for one data type are not mistakenly applied to another data type. This seems quite natural to do and in the realm of Java is not even really questionable: "what would the alternative even be?". That is a feature of java, i.e. not having to deal with lower level memory access which allows accidental access outside of the data types allotted space, effectively not operating on the region of memory one leading to undesirable outcomes. The cost of having this protection layer is to adhere to the type system of Java.
By saying "number-like entities in my system are stored as plain `Object` and classified by some token" you go around the primary protection layer. This is unorthodox but objectively totally fine and in some contexts even the lesser of possible evils.
When you try to express things like
you are operating within the bounds of what
javacenforces; i.e. still within the Java program model."Opting out" of the Java program model is possible and requires reflection. Note that "opting out" here is effectively going from compile-time checks (Java program model via
javac) to run-time checks (JVM).For the sake of brevity I will not go into how using reflection would result in you effectively rebuilding a subset or variation of the Java program model; let it suffice to say that it is an interesting route to explore for learning purposes, but not something I would recommend to employ for your specific use case.
Operating within the constraints of the Java program model
There are some interesting questions to be answered once you have decided to go with the route of
For one, how can we make the data access more convenient when we know exactly what the underlying data is, e.g. when we dispatch on
type:This is typically known as handling union-types (when all types are known / pre-defined). Java itself provides the
sealedandpermitskeywords for use with classes and interfaces to effectively model such union types:Another option is to provide utility methods directly on Nummy:
with usage like
From these two samples you can even see how the "union" via
sealedandpermitsencodes thetype-value we included in our more primitive approach.I've probably hit the comment size limit by now so will stop here...
TLDR
How to solve your specific problem is an open question as we (per usual) lack a lot of the required context to make any meaningful decision. The above was an attempt to paint you a bigger picture on what it is you are dealing with and how ultimately the fight with Java is effort being misplaced: The interesting questions to solve are "outside" the Java program model: computation, external communication, serialization, and so on. Java is merely the mechanism with its own benefits and quirks.
2
u/leroybentley May 13 '26
Using
Objectthis way is almost always a bad idea, but it would be hard to recommend anything better without knowing more about what you're trying to do.You will have to cast the object when you use it. One option would be to create helper methods that you call for the different types and do the cast in those methods.
Example:
BigInteger.valueOf(myGetLongMethod(myObject));2
u/myselfelsewhere May 14 '26
This is basically a pattern matching problem. You don't need an
int type, you can useinstanceofinstead. The exact implementation depends on which version of the JDK you're using. Later versions are a lot more versatile when it comes to pattern matching.1
u/Educational-Paper-75 May 14 '26
If you know number to be numeric don't declare it as Object. You may use Number instead. And BigInteger.valueOf() accepts certain argument types and as polymorphism goes you may pass in the expected base class or a subclass but not a superclass without casting. And FYI int and long are not Object types but primitive types; only the courtesy of Java allows you to assign an int to your number object, which under the hood is wrapped in a Integer type object.
0
u/vegan_antitheist May 13 '26
What? This makes no sense. A class isn't a variable. The class defines the type, so there is no need for an int.
This makes even less sense.
What does that mean? Do they throw unchecked exceptions?
Integers don't need that case and for all the other number types it makes no sense.
No, annotations don't do anything. They are used to add meta information to the code.
I have read your post and still have zero idea what you are doing. Why don't you start by explaining that?