1
Object ele=a.get(i);
if(ele instanceof java.lang.Integer){//cast to integer:
    print("found Int");
}else{ //cast to string:
    print("found: "+ele.getClass());
}
//prints: found: class com.cycling74.max.Atom$IntAtom

This is part of a larger chunk of code but this is the relevant part. I need to know how to check the type of an element in the Atom class by cycling74.

if(ele instanceof com.cycling74.max.Atom$IntAtom)
//ERROR: com.cycling74.max.Atom.IntAtom has private access in com.cycling74.max.Atom

Any ideas?? Thanks a lot - this is really doing my head in!!

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
cronoklee
  • 6,482
  • 9
  • 52
  • 80

3 Answers3

3

Yes, it is possible without making IntAtom public although it is a bit hacky.

First you need to get a reference to the private inner IntAtom class:

public class SomeClass {
  public static final Class<?> INT_ATOM_CLASS;
  static {
    Class<?> [] innerClasses = Atom.class.getDeclaredClasses();
    Class<?> intAtomClass = null;
    for (Class<?> klass : innerClasses) {
      if (klass.getSimpleName().equals("IntAtom")) {
        intAtomClass = klass;
        break;
      }
    }
    INT_ATOM_CLASS = intAtomClass;
  }
}

Then to do the instanceof check:

if (SomeClass.INT_ATOM_CLASS.isAssignableFrom(ele.getClass())) {
   // do stuff
}

Javadoc for Class.isAssignableFrom(Class c);

Matt Wonlaw
  • 12,146
  • 5
  • 42
  • 44
1

I think you'll have to either make IntAtom public, or provide a public function in Atom that can verify whether an object is an IntAtom or not. Right now the class definition can't be compared against because it's private to Atom.

roberttdev
  • 42,762
  • 2
  • 20
  • 23
  • Hmm, thanks @roberttdev It sounds complicated. I dont have access to the Atom class tho. It's an API built into MaxMSP software. Also, if I did have access,I wouldnt know where to begin doing that as I'm brand new to java! (this is my first project!). Is there any hacky workaround I might be able to try?? – cronoklee Mar 30 '11 at 16:16
  • The only thing I can think of is to subclass Atom and make the change yourself. It's not pretty.. but I don't know how else you can access that private class. Double check the API to make sure they don't offer something for this first. – roberttdev Mar 30 '11 at 16:20
  • your subclassing solution won't help as private classes isn't inherited by the subclasses. – Buhake Sindi Mar 30 '11 at 16:22
  • it is *possible* to do it without making IntAtom public, although not necessarily advisable. See my answer below. – Matt Wonlaw Mar 30 '11 at 16:34
0

Thanks a lot fellas - it seems the Atom class has a method somewhere called isInt() that can check the built in datatype. I wouldnt have looked for it had you guys not got back so I really appreciate the help!

cronoklee
  • 6,482
  • 9
  • 52
  • 80