Nothing specifically related to Android: more a java question while
struggling making the switch from objective c to java:

1. In Java static methods when implemented in derived classes are
hidden, not overridden. If I have a method foo() in class A and B.
Execution of: A b = new B(); b.foo() will execute method foo() in
class A. That causes me a problem because if I use factory methods in
classes, for each subclass I need to reimplement the static factory
method. I was wondering how people solved this with or without
reflection (I am okay paying the performance toll at object creation).

2. I am trying to replicate the easy functionality of the
NSClassFromString method. Basically, if I have a string for a full
qualified class name, what is the best way to invoke a static method
with a known signature for that class.

In objective c:

Class foo()
{
        NSString *r = @"Bar";
        Class c = NSClassFromString(r);
        return c;
}

then you can call method sna() on class Bar with [foo() sna:d]

So far in Java using reflection, I came up with this convoluted code
that doesn't replicate the behavior for the parameters for the
function (I pass back the object reference, not the method back,
therefore I also have to pass the parameter to call the method):

static SuperClassOfBar foo(float d) {
        try {
            String r = "Bar";
            Class c = Class.forName("com.example."+r); // Fully
qualified name for class
            Class partypes[] = new Class[1];
            partypes[0] = Float.TYPE;
            Method m = c.getDeclaredMethod("sna", partypes);
            Object arglist[] = new Object[1];
            arglist[0] = d;
            Object o = m.invoke(null, arglist);
            return SuperClassOfBar.class.cast(o);
        } catch (Exception e) {
            return null;
        }

It works but it's heavy and not pretty. I understand that leaving a
dynamic language like objective c , I have to make some compromises,
but I may miss something about Java for not having found something
more lightweight for such a generic programming functionality. Any
suggestions to simplify this implementation are welcome.

Thanks in advance.


-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to