Typecasting using Reflection

Hi !
How do I type cast classes using reflection?
I use my own classloader and load a few classes, say 'myinterface', 'myinterfaceimpl' and 'someclass' in that custom classloader.
'myinterface' class is public where as the implementation class, 'myinterfaceimpl', access is private. 'someclass' has a method whose return type is 'myinterface', and it returns an object of instance 'myinterfaceimpl' (which is an innerclass).
1. My application starts with the system classpath (where the above 3 classes are not present).
2. My classloader loads these 3 classes.
3. Using reflection, I invoke the specified method in 'someclass', whose return type is 'myinterface'.
4. Now I am unable to invoke a public method defined in the interface, since the implementation class level access is private. I get an IllegalAccessException, when I try to invoke a method in the object returned.
5. I feel it would work, if I can somehow typecast the object returned from the method invocation to the interface class and then invoke the method.
6. The same scenario works when I don't use reflection and have them in the classpath.
Any help would be greatly appreciated. I saw a few postings related to this in the forum, but I am unable to find an answer.
Best Regards,
Ramesh.

4. Now I am unable to invoke a public method defined
in the interface, since the implementation class level
access is private. I get an IllegalAccessException,
when I try to invoke a method in the object returned.Private methods cannot be used to implement methods that the interface specifies to be public, as far as I know. A class that claimed to implement an interface that way should not compile.
5. I feel it would work, if I can somehow typecast the
object returned from the method invocation to the
interface class and then invoke the method.
6. The same scenario works when I don't use reflection
and have them in the classpath.Perhaps the class you have doesn't claim to implement the interface, but just happens to have methods with the same signature, although some of them are private? If that's the case then you have a design problem that should not be worked around this way. Fix the class to implement the interface properly and you won't have to deal with any of this nonsense.

Similar Messages

  • How can i get all java class names from a package using reflection?

    hi,
    can i get all classes name from a package using reflection or any other way?
    If possible plz give the code with example.

    You can't, because the package doesn't have to be on the local machine. It could be ANYWHERE.
    For example, via a URLClassLoader (ie from the internet) I could load a class called:
    com.paperstack.NobodyExpectsTheSpanishInquisitionI haven't written it yet. But I might tomorrow. How are you going to determine if that class is in the package?
    This subject comes up a lot. If you want to do something a bit like what you're asking for (but not quite) there are plenty of threads on the subject. Use google and/or the forum search facility to find them.
    But the answer to your question, as you asked it, is "you can't do that".

  • Calling a pkg from managed code and then using reflection to call a method from a script task

    Hi we run 2012 std.  I have some pretty good evidence that when I call my pkg from a .net service, a script component in that pkg fails when trying 2 use reflection to load and invoke our .net message history method.  The exception is either on
    the invoke or in the message history method.  I suspect its in the method but will take additional steps 2 verify.
    But when I run the pkg stand alone, it has no problem and the method does what it is supposed 2 do.
    There r no vars passed from the service to the pkg.  I wonder if its a managed to unmanaged to managed issue that the community is already aware of.  If not, my apologies 4 posting this quickly.
    I'll post more info here as I collect it. 

    we have 2 theories after showing the exception trace to folks who r more adept at managed code.
    the first is related to the fact that our 3rd party dlls (I think entity framework is included in these) r older versions.  I don't want to discount this theory but we have some evidence already that this might not be true.
    I hope I can do justice to the 2nd theory but will make it clearer and clearer as I get a better understanding.  I believe this is what Arthur was saying and I applaud his instincts.  They explained that .net is so "smart" that it detected
    a change in namespace  (ie context as Arthur said) and purposely threw an exception 2 save us from ourselves.  The workarounds discussed were a bit over my head but I will continue trying to better understand it.  The fact that many of the methods
    we call after reflection r now merged into one assembly seemed relevant to the discussion and possible workarounds.   
    this link came up in their discussion and I believe the bottom line here is that by qualifying assembly names further (in config?)r, a workaround is possible. 
    http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx  .
    This link came up as well and has something to do with ILMerge and workarounds to ILMerge. 
    http://elegantcode.com/2011/04/02/dynamically-load-embedded-assemblies-because-ilmerge-appeared-to-be-out/  .
    Finally, this link came up and seems to have something to do with embedding your dlls in one assembly without them losing their identity.
    http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
    I'll post more here as we muddle thru this.

  • XML document creation using reflection

    Hi all,
    I'm tyring to write a class which creates an XML document from objects passed in. For example, you call the add(Object) method and it takes your object, uses reflection, then outputs XML like this...
    <fieldName>fieldValue<fieldName>
    The only problem is that after looking through this forum I am a little concerned about the performance of my proposed solution (using reflection).
    The class will be used in a batch process which processes millions of objects (to generate a whopping XML file that'll be sent on for further processing by a third party).
    Is there a better way to do this than by using reflection?
    This class is going to be used by multiple batch processes hence there will be lots of different object types passed (they'll also be new ones in the future that we don't even know about yet) hence my reflection choice.
    Thanks,
    Chris

    The only problem is that after looking through this
    forum I am a little concerned about the performance of
    my proposed solution (using reflection).The only way that you'll know for sure is if you try it out. Write the code, test it, then run it in a profiler to find out where the performance problems (if any) are.
    Is there a better way to do this than by using
    reflection?Probably not, if you want to pass any arbitrary object to it.
    One possible alternative is to have "XML aware" objects: define an interface WritesXML, that defines a method toXML(). You then check to see whether the given object implements this interface, and if it does you simply call the method, otherwise you use reflection.
    Another alternative, assuming that your objects follow the Bean pattern, is to create "XML-ifiers" on the fly, similar to the way an app-server handles JSPs. First time you see an object you create a class that will write it to XML, then compile this class and invoke it for all subsequent objects. This will require that you have a JDK installed on the runtime machine, that the objects follow the Bean pattern, and that the number of instances of a given class are very high.
    This class is going to be used by multiple batch
    processes hence there will be lots of different object
    types passed (they'll also be new ones in the future
    that we don't even know about yet) hence my reflection
    choice.Sounds like a good reason to use reflection.

  • Using reflection...

    Hi,
    I have one class. to run that, I am calling like the following...
    java -classpath ;.;\comdotebo; com.pack1.MyClass
    now I want to take the reference of this class(dynamically) using reflection pakcage like the following...
    Class cla = Class.forName("com.pack1.MyClass");
    but to take the class reference I need to set the classpath;
    so how can i set the classpath dynamically.
    please give proper solution
    thanks
    Raja Ramesh Kumar M

    here the case is we know both the class and the class path at run time only
    for ex: see the following.....
    I have two files .....
    1) c:\dir1\com\pack1\MyClass1.class
    2) c:\dir2\com\pack2\MyClass2.class
    now I want to access both the classes using reflection from ...
    c:\dir3\com\pack3\MainClass.class
    using reflection, we can write the following...
    Class clas1 = Class.forName("com.pack1.MyClass1");
    if I am taking like this, then I am getting ClassNotFoundException.
    becoz, for that we have to give the proper classpath before running the program.
    like.
    set classpath=%classpath%;.;c:\dir1;
    but my problem is here I know the the class name (for ex: com.pack1.MyClass1) and the classpath (ex: c:\dir1)
    at runtime only.
    so please tell me how to solve this problem
    regards
    Raja Ramesh Kumar

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

  • Creating objects using reflection

    Hi,
    I need to construct a new instance using reflection and passing parameters. If the parameters are of primitive type ex. int, how can I pass them in the Class[] type of object

    Integer.TYPE, etc. are Class objects that represent the types of the primitives.

  • Get Name of Variable using Reflection

    Is there a way to get the variable name?  I assume I'd have to use Reflection.  Here's an example of what I mean.
    Dim tileCount As Integer
    ' get tileCount variable name here
    Debug.Print("tileCount")
    Ryan

    I need to validate a variable.  If the variable isn't valid I want to throw an ArgumentOutOfRangeException.
    Variable names are internal to your program.  They don't actually exist as part of your executable code, but it is possible with reflection to look back into the source code and find certain information.   But it is not possible
    to identify a variable by its value. However, you should not be using variable names to identify your objects.
    If you create a class for your values then you can build a IsValid test for the value field of the class, and return information about the class instance.  For example:
    Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim thisTile As New Tile With {.Height = 7, .Name = "Fred"}
    If Not thisTile.IsValidHeight Then
    Throw New ArgumentOutOfRangeException("Instance", thisTile.Name, String.Format("{0} is not a valid tile height.", thisTile.Name))
    End If
    End Sub
    End Class
    Public Class Tile
    Public Name As String
    Public Height As Integer
    Public Function IsValidHeight() As Boolean
    Dim myArray() As Integer = {3, 4, 6, 7}
    If Not myArray.Contains(Me.Height) Then
    Return True
    Else
    Return False
    End If
    End Function
    End Class
    Great idea! :)
    Still lost in code, just at a little higher level.

  • Using Reflection can we find out details of inner classes in a class

    Hello All,
    Thanx in advance.
    I intend to figure out the name of the inner class and methods declared inside it. How can this be done using reflection API's.
    I need the above information to make an automated java doc creation tool for the project I am working in.
    Thanx again...
    VIkas

    Thanx silkm,
    Actually suggestion # 1 I have already tried. I used
    getClasses() method which returned me a Class[] of
    length = 0. i dunno Why?Because you are not using the reflection API correctly. If you read the javadocs you would know that it is structured so that all getXXX() methods return all XXX things that are public and are either declared by the target class or possibly inherited from superclasses.
    As contrasted to that, getDeclaredXXX() methods can return all XXX things (including private) but only declared by the target class (not inherited).
    You got an empty result back in your case most likely because all your nested/inner classes were non-public. Use getDeclaredClasses() instead.
    As to suggestion # 2, the exercise I am doing is a
    step before using the java doc tool. One has to insert
    a javadoc comment before the method begins in order to
    create a java doc. So thats it.This is independent of the reflection API but you might consider using the doclet API for this.

  • Problem using reflection... Really urgent...

    Hi all,
    in my current program, i'm usin reflection a lot. This is due to the fact that i automatically generate some code, compile it, and run another program which uses the generated code.
    The generated code contains inner classes. For example:
    package mypackage;
    class A {
    public A() {}
    class B {
    public B() {}
    class C {
    public C() {}
    My question is: how can i instantiate, the classes B and C using reflection? i think i tried everything but when i run my prog i keep having error messages such as:
    - InstantiationException
    - NoSuchMethodException
    -etc...
    Any idea?
    Jack

    Consider this:
    Can you make the inner clases static? If you do, you may instatiate them by using names like A.B and A.B.C.
    If the inner classes are not made static, they need an instance of the enclosing class in order to be instantiated. This basically means that you may instantiate a B from inside a (non-static) method (or constructor) in A, and a C from within a method in B.
    One way of doing this is to create a method on A that creates a B (a factory method). Then, in order to get a B you first create an A, then call the factory method to get a B. By putting a factory method for C's in B, you could then go on to create a C from the B.
    But before going into this, you should consider whether you really need the inner classes to be non-static.

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Update problem when using reflection

    We have an issue when updating objects. The values are not updated in the DB when we set the values in the domain class using reflection. However when we explicitly set the values using the setter methods, update is ok.
    Here is the code for the reflection mechanism:
    UnitOfWork uow = session.acquireUnitOfWork();
    //domain class which needs to be persisted
    Student student = new Student();
    //get the clone
    Student studentClone = (Student) uow.registerObject(student);
    //copy the values from the value object into the
    // domain class using reflection
    studentClone.setVo(studentVo);
    uow.commit();
    The setVo method uses reflection to set the values (using invokeMethod). The values are set properly in the domain object. But the values are not updated when we do the commit.
    However, if we explicitly set the values in the clone using the "setter" methods, update is okay. So this code works fine.
    UnitOfWork uow = session.acquireUnitOfWork();
    Student student = new Student();      
    Student studentClone = (Student) uow.registerObject(student);
    studentClone.setName("NBA"); //set the value of name
    uow.commit();
    Any ideas would be appreciated...
    Thanks much

    TopLink 10.1.3 tracks changes through working and backup copies by default, so even if you set your changes through reflection they should be picked up. If you were using CMP 2 or EJB 3 or explicitly enabled AttributeChangeTracking, then changes set through reflective field access could be missed. In this case you should use the set methods through reflection, instead of the field directly.
    I would check your code that set the changes through reflection, perhaps it is not working as you expect. Check the state of the object after applying the changes and verify they were actually set. Also ensure that you are changing the UnitOfWork clone, not the original object.

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

Maybe you are looking for