I need some eyes on this code.

  • Thread starter The Abrasive Sponge
  • Start date
T

The Abrasive Sponge

Shouldn't this work?


//Source Java 1.5/5.0
public class AssignableFromTest {

/** Creates a new instance of AssignableFromTest */
public AssignableFromTest() {
}

private static boolean isStandardProperty(Class<?> clazz) {
if (clazz.isPrimitive()) return true;
if (clazz.isAssignableFrom(Number.class)) return true;
if (clazz.isAssignableFrom(Character.class)) return true;
if (clazz.isAssignableFrom(String.class)) return true;
return false;
}

public static void main(String... args) {
Byte b = new Byte("0");
System.out.println(isStandardProperty(b.getClass())); //false?
Integer i = 4;
System.out.println(isStandardProperty(i.getClass())); //false?
}
}
 
T

The Abrasive Sponge

The said:
Ryan said:
Ryan Stewart wrote:

message

Shouldn't this work?


[...]
It works fine for me. What do you find to be wrong with it?


Did you get 2 false or 2 true?



two false
Hmm, I would of thought that it would be two true since Byte and Integer
are subclasses of Number.


Nevermind I see why, just read the java doc.
 
R

Ryan Stewart

The Abrasive Sponge said:
Hmm, I would of thought that it would be two true since Byte and Integer are
subclasses of Number.

But that's the reverse of what you're asking. Your code checks if "Byte is
assignable from Number" and if "Integer is assignable from Number". In code,
that would be:
Number n;
Byte b = n;
Integer i = n;

That won't work without explicit casting. Read the method contract in the
java.lang.Class docs.
 
R

Roland

Ryan said:
Ryan Stewart wrote:

message

Shouldn't this work?


[...]
It works fine for me. What do you find to be wrong with it?


Did you get 2 false or 2 true?



two false
Hmm, I would of thought that it would be two true since Byte and Integer
are subclasses of Number.

isAssignableFrom can be confusing. I always try to read it it the other
way round. So
if (clazz.isAssignableFrom(Number.class)) ...
would become
if [an instance of] Number.class can be assigned to [a variable of
type] clazz ... [then]

And this isn't what you expected it to do... ;-)
You probably want to test
if [an instance of] clazz can be assigned to [a variable of type]
Number ...

--
Regards,

Roland de Ruiter
___ ___
/__/ w_/ /__/
/ \ /_/ / \
 
D

dar7yl

The Abrasive Sponge said:
Nevermind I see why, just read the java doc.

Darn, just when you had a theory all figured out, somebody has to go and
write the docs to bust it out of the water :)

regards,
Dar7yl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top