Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

disabling automatic type casting

 
raj kothari
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing an method which take int as input. I want to ensure that the argument received is exactly of int type and not of byte, short, char.
Like that I am writing many methods in which I expect the exact variables. How can I disable the automatic type conversion at the method level, and how do I check the exact type else give the error to calling function and return.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't.

If the formal parameter is an int, the actual parameter can be an int or any smaller integral type. You can't tell what it was.

What is the higher-level thing that you're trying to achieve? Since your suggested approach is impossible, you will have to think of another approach to achieve the same higher-level feature.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... I suppose you could overload the method to "catch" narrower types.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would happen if you used Integer instead of int? You would get autoboxing, so an int would be acceptable. I tried it with a short, and it wouldn't compile.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you explain why you have this requirement that the argument must be exactly of a specific type? I'm curious why you would need this, and I can't think of what problem this would solve.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems like I missed some possible approaches that, while not what the original poster asked for (which remains impossible), are quite close. Well done other bartenders!

However, the requirement still seems bizarre and pointless. Unless it's an interview/homework question, we need to know what the real higher-level requirement is.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic