Method Reflection Woes

I'm trying to figure out if I can get type safety from a method signature such as:
public Object getByType(Class type);Where the resulting object is an instanceof Type. Is this even possible to do with generics?

You can parameterize a method as well as a class, so your method signature becomes
public <T> T getByType(Class<T> type);Note that the type T is independent of any generic type defined by the class to which your method belongs. You can then use your method as follows (where Base and Sub are two random types, whereby Sub extends Base):
Class<Sub> type = Sub.class;
Base instance = getByType(type);There are two things to note here. The first is that the return value of the method is now of type Sub, rather than Object, so a cast is not required in the assignment to instance. The second is that it's not possible to pass in a Class instance of an inappropriate type without the compiler complaining.

Similar Messages

  • Excel with powershell and this big problem of locale

    Hi Folks, I'm getting C R A Z Y with this Excel/Powershell Stuff...
    MY display language is EN
    My input language is fr_CH
    the following code : 
    function Invoke([object]$m, [string]$method, $parameters)
    $m.PSBase.GetType().InvokeMember(
    $method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters,$ciUS)
    $ciUS = [System.Globalization.CultureInfo]'fr-CH'
    $objExcel = New-object -com Excel.Application
    $objExcel.visible = $True
    $ci = [System.Globalization.CultureInfo]'fr-CH'
    $objWorkbook = Invoke $objExcel.Workbooks Add
    $objWorksheet = $objWorkbook.Worksheets.Item(1)
    $objWorksheet.Cells.Item(1,1).FormulaLocal = "A value in cell A1."
    Invoke $objWorkbook SaveAs "C:ScriptsTest.xls" > $null
    Invoke $objWorkbook Close 0 > $null
    $objExcel.Quit()
    throw me the error : 
    Exception calling "InvokeMember" with "6" argument(s): "Object does not match target type."
    At line:3 char:1
    + $m.PSBase.GetType().InvokeMember(
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : TargetException
    You cannot call a method on a null-valued expression.
    At line:11 char:1
    + $objWorksheet = $objWorkbook.Worksheets.Item(1)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    Basically this happend when you have english Excel with non english locale.
    My OS is in english but my Keyboard is in French-Swiss.
    Please help me I'm getting crazy...
    MCITP Enterprise Administrator / Server Administrator

    This might be helpful.
    http://dmitrysotnikov.wordpress.com/2008/02/22/powershell-help-broken-on-localized-versions-of-windows/
    The problem seems to be that PowerShell v1 for Windows Vista and PowerShell v2 CTP for all systems are storing the language neutral (English) help system in the en-US subfolder of the PowerShell folder.
    On a localized versions of Windows, PowerShell seems to be looking for a subfolder with its own locale (e.g. de-DE for Germany, ru-RU for Russia, and so on) and does not fail over to en-US if the folder is not found.
    RESOLUTION
    Apply the language pack for your language so your local version of help gets added to the system.
    If the language pack is not available, copy or rename the en-US folder to match your Windows locale. To learn your locale run the following command in the PowerShell prompt:
    [System.Globalization.CultureInfo]::CurrentUICulture
    Thanks Azam When you see answers please Mark as Answer if Helpful..vote as helpful.

  • Pickup a class in application without bouncing the WLS

    Hi,
    I've an application(deployed on WLS) which basically takes the name of a class and delegates it to another process, which then loads the class and calls a few methods reflectively. For this, I want the second process to reference to a directory(outside the ear) so that it looks for the resolution in this directory.
    Now, the problem is, how to make the application refer to this directory. I do not want them to be loaded by server classloader as they will unnecessary be available to all other applications. So, adding the name to server classpath or deploying it as shared library is ruled out.
    Other requirement is, the jar file can be introduced dynamically by a user into the directory and the application should take care of it for any references. Bouncing application should do this needful.
    Does WLS have a feature to cater to this need?
    Thanks.
    Nitin

    hi thanks at first,
    the thing you mentioned could be a problem, but I dont think it is.
    If I have the full qualified name (which I havent) then everything goes normal. I only have to load the "twoButtons" class and not the other (actionadapter class), so I dont think this is the point. In this case the twoButtons constructor constructs an object of the actionadapter class and everything goes well. The bad thing is though that I do not have the full qulified name :(
    Invocation target exception tells me (in own words): Tried to acces the constructor of the actionadapter class (which is not public) out of class reflectionTest class .
    reflectionTest is the class where the reflection stuff happens and the twoButttons class is defineClass() ed.
    The problem is, only twoButtons class has the rights to call methods from the actionadapter class, the reflection class does not. BUT: I do not call the actionadapter methods from the reflection class. I call them only from the twoButtons class.
    I hope somebody understands my problem :)

  • Covariant Return Types - J2SE 5.0

    I just read the tech tip regarding the new covariant return types in j2se 5.0
    In the doc, it said that you can now compile two methods with the same signature but with different return types. I was wondering if anyone knew how this would affect what the following expression returns: anObject.getClass().getMethod(aMethodNameString, aClassArray)
    If there are two methods with the same signature except for the return type, how does the above expression know which method to return?

    Never mind, I just found my answer in the javadoc....
    "To find a matching method in a class C: If C declares exactly one public method with the specified name and exactly the same formal parameter types, that is the method reflected. If more than one such method is found in C, and one of these methods has a return type that is more specific than any of the others, that method is reflected; otherwise one of the methods is chosen arbitrarily. "

  • To get the reflection of a variable arity method.

    Hi,
    I am having
    public static Object myMethod(Object... args)I need to return the rfletion of this method. I have tried out the following, but it throws an error of mismatch in the number of arguments when I pass more than one argument.
    return cls.getMethod("myMethod", Object[ ].class);Please help in this regard.
    Thanks in advance.

    public class Test  {
        public static void main( String argv[] ) throws Throwable {
         Class cls = Test.class;
         System.out.println( Object[ ].class );
         java.lang.reflect.Method m = cls.getMethod("myMethod", Object[ ].class);
         Test t = new Test();
         Object[] paramsA = new Object[0];
         System.out.println( m.invoke( t, new Object[] { paramsA } )  );
        public  Object myMethod( Object... a ) {
         return "Test";
    }seams to be working for me. Could your post your error message? Thanks

  • 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.

  • Reflection and the field.set method

    OK, I've made 2 classes, a ClearParent and ClearChild (which extends ClearParent). I'd like to have a "clear" method on the parent which dynamically sets all the fields to null. I'd like to be able to have any child that inherits from the parent be able to call clear and dynamically have all it's fields set to null.
    Part of the restriction that I'm facing is that the fields are Objects (Integer) but the getter and setter methods take and return types (int). So I can't just loop through the Methods and call the setters with null.
    I'd like to be able to loop through the fields and call set for all the fields with the parent class.
    I'm inserting the code that I have for the parent and child classes at the end. Basically, the problem that I'm seeing is that if I do a
    this.getClass().getName()
    from the parent (when clear is called from the child) it shows me the child name ("ClearChild"). But when I try to do the
    field.set(this, null)
    it tells me this:
    Class ClearParent can not access a member of class
    ClearChild with modifiers "private"
    How come when I get the name it tells me that it's the child but when I pass "this" to the set method, it says that it's the parent?
    Any one know what's going on here? Is there anyway that I can have the parent set all the fields to null?
    Thanks in advance.
    Here's the code:
    ClearParent
    import java.lang.reflect.*;
    public class ClearParent {
        public boolean clear() {
            try {
                System.out.println(this.getClass().getName());
                Field[] fields = this.getClass().getDeclaredFields();
                Field   field;
                for (int i = 0; i < fields.length; i++) {
                    field = fields;
    field.set(this, null);
    } catch (Exception e) {
    e.printStackTrace();
    return true;
    ClearChild
    public class ClearChild extends ClearParent {
    private Float f;
    public ClearChild() {
    super();
    public float getF() {
    if (f == null) {
    return 0;
    return f.floatValue();
    public void setF(float f) {
    this.f = new Float(f);
    public static void main (String[] args) throws Exception {
    ClearChild cc = new ClearChild();
    cc.setF(23);
    cc.clear();
    System.out.println("cc.getF: " + cc.getF());

    It is an instance of ClearChild that is being used so
    that class name is ClearChild. However, the method
    exists in the parent class and thus cannot act upon a
    private field of another class (even if it happens to
    be a subclass).Ahh...makes sense.
    Why don't you just override clear in the child?We were trying to avoid this because we run into problems in the past of people adding fields to the class, but not adding to the clear, and things not being cleared properly.
    I talked it over with the guys here and they have no problem making the fields protected instead of private. If it's protected, then the parent has access to it and my sample code works.
    Thanks for your help KPSeal!
    Jes

  • Using java.lang.reflect.Method.invoke on a static method?

    This is probably a FAQ, but I am finding it impossible to construct a search which answers this question for me.
    How do I call java.lang.reflect.Method.invoke on a static (e.g. class) method? Is it even possible?
    Thanks,
    dwh

    Is this of any help?
    http://www.esus.com/javaindex/j2se/jdk1.2/javalang/reflection/reflection.html
    Cheers,
    Joris

  • Using Reflection - Method.invoke()

    Hi all,
    Facing a problem in using the Reflection API. Can anyone tell me how to use the invoke, which is available with Method. Problem statement. - I want to create a method. And then invoke that method using method1. invoke. But this can take only the following arguments - (Object, Object [ ] ). I cant figure out why I need to pass on an object ? and an array of objects ?

    If you read the docs for Method.invoke, you'll see that the first argument is the object on which you wish to invoke the method, and the second argument is the parameters (with primitives wrapped appropriately).
    foo.bar("abc", 123);
    // becomes
    meth.invoke(foo, new Object[] {"abc", new Integer(123) }); (if I haven't screwed up the syntax of the array initialization)
    http://java.sun.com/docs/books/tutorial/reflect/

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Reflective invoke of variable-argument method?

    I'm having trouble reflectively invoking a variable-argument method. Can anyone provide a code snippet that does it? Here's my test, with the output below:
    package comet.pod;
    import java.lang.reflect.Method;
    public class Test
       public void doSomething (Object... args)
          System.out.println ("hello world");
       public void test()
          Method method = null;
          try
             Class<?> c = Test.class;
             Class[] argTypes = new Class[] { Object[].class };
             method = c.getMethod ("doSomething", argTypes);
             System.out.println ("is VarArgs? " + method.isVarArgs());
          catch (Exception x) { System.err.println (x); }
          try
             method.invoke (this, (Object[]) null);
          catch (Exception x) { System.err.println (x); }
          try
             method.invoke (this, new Object());
          catch (Exception x) { System.err.println (x); }
          try
             method.invoke (this, new Object[] { "arg" });
          catch (Exception x) { System.err.println (x); }
       public static void main (final String[] args)
          new Test().test();
    }is VarArgs? true
    java.lang.IllegalArgumentException: wrong number of arguments
    java.lang.IllegalArgumentException: argument type mismatch
    java.lang.IllegalArgumentException: argument type mismatch

    You need something like:
    method.invoke(this, new Object[] { new Object[] { "arg1", "arg2" } });To see why, consider what you would do if your method was:
    public void doSomething (Object a1, Object a2, Object... aVar)Alex

  • Reflecting methods of parent class

    I have a class named ParentClass with a public method named getName that takes a String as a paramenter and returns a String.
    If I extend ParentClass, how can I use reflection to access the getName method of the parent (super) class? I get a NoSuchMethodException if I try to get the subclass to reflect any methods it inherits from its parent.

    Also ,I modified the above example to print the method return value . It work fine.
    import java.lang.reflect.Method;
    public class TestReflection {
         public static void main(String[] args) throws Exception{
              SubClass cls = new SubClass();
              Method m = cls.getClass().getMethod("getName", new Class[] {String.class});
              System.out.println(m.invoke(cls,new Object[] {new String("testing name")}));
    class ParentClass {
         public String getName(String s) {
         return s;
    class SubClass extends ParentClass {}

  • Invoking a method using reflection with json data as argument

    Hi,
    I want to invoke a method using reflection and this method have one argument . Now I want to pass a json data as an argument to this method .Please see the following code.
    int HelloWorld(int Id){
    return Id;
    json data{"Id":43}
    how can I use the reflection to use the json.
    Please provide your guidelines

    Thanks for your reply, I am building a windows console application .And I want to convert the json data to object array to use in Method Base.Invoke method.
    Regards,
    Ethan
    Maybe you could select the correct language development forum here:
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages&filter=alltypes&sort=lastpostdesc
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to stop/kill/interrupt a thread stuck on reflection method invoke

    Hi all,
    I have a thread that loads some class using reflection and invokes a method in it.
    I want to be able to stop that thread if needed by the user.
    For some reason, interrupt on that thread doesn't do anything - thread is still inside the invoke call.
    Is there any way to stop it?

    The only really safe way to have isolated code is to a seperate process you can kill.
    I wouldn't suggest using Thread.stop unless you have to, but that may be the case here. Stopping the thread this way might be worse than just discarding the Thread and moving on. (depending on what it is doing) i.e. another option is to ignore the thread and hope it doesn't matter. ;)
    However, before you do that I suggest you call Thread.getStackTrace() and log it. This can be useful in diagnosing WHY your thread needed to be kill and possibly give you a chance to fix it next time.

  • Dynamic method call needs reflection class?

    Hi,
    First of all, this is my first post so go easy on me ;)
    I would like to have something like this in Java:
    String name = "number1";
    int temp = name + getme();
    the integer temp should now be the result of the method "number1getme()".
    By changing the value of 'name' I could get the value of number2, number3 etc. etc.
    Hope you understand and can help.
    Yours Sincerely,
    GrandiJoos

    If you really want to do it this way, you will indeed need to use reflection. Have you considered other options, such as storing values in a Map or creating one getme() method that takes a name argument?Map<String, Integer> temps = new HashMap<String, Integer>();
    .. fill the map with temperatures
    String name="number1";
    int temp = temps.get(name);orString name="number1";
    public int getme(String name) {
    int result = ...;
    if(name.equals("number1")) {
      result = <some temp here>;
    return result;
    }

Maybe you are looking for

  • Windows Server TechNet Guru News: October Winners Announced

    All the votes are in!  And below are the results for the TechNet Guru Awards, October 2014 !!!! For a full list of winners, see the full blog post, as runners up had to be removed from this post to fit the forum max length restrictions.  BizTalk Tech

  • Lenovo Tablet 2 Installation Problems - Help would be GREATLY appreciated as Lenovo WILL NOT HELP.

    Hi everyone.  I've been pulling my hair out with this and I'm just about at my breaking point after 15 some hours of messing with this but I thought I would give it one last shot. I have a Lenovo Tablet 2 that originally came with Windows 8 and later

  • WEBUTIL DIALOG BOX NOT OPENING

    hi all I have an issue with webutil when i am triyng to execute webutil_clientinfo.get_user_name in when button pressd triger. Below error I am getting. oracle.forms.webutil.file.FileFunctions bean not Found.WEBUTIL_FILE.FILE_SELECTION_DIALOG_INT WIL

  • Background expandable for new text??

    Here is a link to the website I am building first off. My issue is that my background is not getting larger or smaller with the amount of text.  On my home page there is like a bulletin box with text on it. As of right now I have to edit the wording

  • SAP HR - RP_PLAN alphanumeriacal number range in SNRO

    Hi guys!! I have an issue regarding number range in Organizational Management for SAP HR. We have internal and external intervals and that's ok however, it's required to maintain external alphanumerical number range for positions, jobs and organizati