簡體   English   中英

如何使用反射 API 調用 Setter 方法但沒有提到像 FieldName 和 MethodName 這樣的東西

[英]How To Invoke Setter Method using Reflection API But does not mention anything like FieldName & MethodName

如何使用反射 API 調用 setter 方法。 但問題是我們沒有指定 Field Name , Method Name 之類的

Method method = User.class.getDeclaredMethod("setName", String.class);
method.setAccessible(true);
method.invoke(user, "Some name");

還有這個

TestClass igsm = new TestClass();
      User user = new User();   

    Method methodName= igsm.getMethod("name",user.getClass(),"setter");
    methodName.setAccessible(true);
    igsm.invokeSetter(user,"Sanket",methodName); 

在這種情況下,我們只指定方法名稱、字段名稱,然后我們設置方法名稱、字段名稱的值基礎。

我想不指定任何東西。 並檢查調用哪個 setter 方法的值的基礎。我不能在程序中硬編碼任何東西。 並提取有關運行時的所有信息並在適當的方法中設置值。

這樣我們就可以很容易地通過反射調用私有的 setter 方法。 我只指定了該值,然后它將確定要調用哪個 setter 方法。

//MainMethod

    public static class InvokeMain 
        {
            public static void main(String... args) throws Throwable 
            {
                Object obj1 = getBean("www.Fouth.User");

                System.out.println(obj1.toString());
            }

        }

    //Customize Method


      public static void extractMethod(Method[] method,Object valueObj,Object classObj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
        {
            for(Method m:method)
            {   
                Type[] pType = m.getGenericParameterTypes();

                for(int i=0;i<pType.length; i++)
                {
                    System.out.println("The pType[]"+pType[i]);         

                    if(valueObj.getClass().equals(pType[i]))
                    {   
                        m.setAccessible(true);
                        m.invoke(classObj,valueObj.getClass().toString().valueOf(valueObj));
                    }
                }
            }

        }

      //ReflectionMethod


    public static Object getBean(String beanClassName) throws Exception
        {
            Class klass = Class.forName(beanClassName);
            Object obj = klass.newInstance();               
            Method[] b = klass.getDeclaredMethods();

            RefLevel3.extractMethod(b,"sanket",obj);
            RefLevel3.extractMethod(b,23,obj);


            return obj;
        }      

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM