예제 #1
0
 private static <T> void fillWithConstructor(
     @NonNull final CursorGetter getter,
     final List<T> lists,
     final @NonNull Constructor<T> constructor) {
   try {
     while (getter.moveToNext()) {
       lists.add(constructor.newInstance(getter));
     }
   } catch (final InstantiationException e) {
     throw new IllegalArgumentException(
         "go and make the constructor "
             + constructor.getName()
             + "(CursorWrapper.CursorGetter) accessible",
         e);
   } catch (final IllegalAccessException e) {
     throw new IllegalArgumentException(
         "go and make the constructor "
             + constructor.getName()
             + "(CursorWrapper.CursorGetter) accessible",
         e);
   } catch (final InvocationTargetException e) {
     throw new IllegalArgumentException(
         "go and make the constructor "
             + constructor.getName()
             + "(CursorWrapper.CursorGetter) accessible",
         e);
   }
 }
예제 #2
0
  /**
   * Finds constructors of the specified access level in the supplied class.
   *
   * @param c the class to search in
   * @param level the access level to look for
   * @param sb the StringBuffer where the results should be added
   */
  private static void listConstructors(Class c, int level, StringBuffer sb) {
    Constructor[] constrs = c.getDeclaredConstructors();
    Constructor constructor;
    Class[] exceptions;
    StringBuffer cons;

    for (int index = 0; index < constrs.length; index++) {
      constructor = constrs[index];
      if (isAccessible(constructor.getModifiers(), level)) {
        cons = new StringBuffer(100);
        cons.append(printConstructor(constructor.getName(), constructor.getParameterTypes()));
        // Add exceptions
        exceptions = constructor.getExceptionTypes();

        if (exceptions.length > 0) {
          cons.append(printExceptions(exceptions));
        } else {
          cons.append(NIL);
        }
        cons.append(END_PAREN);
        if (sb.toString().lastIndexOf(cons.toString()) == -1) {
          sb.append(cons);
        }
      }
    }
  }
 public static void main(String[] args) throws Exception {
   Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy");
   Object object = clazz.newInstance();
   Method[] methods = clazz.getMethods();
   StringBuffer sb = new StringBuffer();
   sb.append("public class ")
       .append(object.getClass().getCanonicalName())
       .append("{\n")
       .append("Object object ")
       .append("\n");
   Constructor[] constructors = clazz.getConstructors();
   for (Constructor constructor : constructors) {
     sb.append("\npublic ").append(constructor.getName()).append("(");
     Class<?> p[] = constructor.getParameterTypes();
     for (int j = 0; j < p.length; ++j) {
       sb.append(p[j].getName() + " arg" + j);
       if (j < p.length - 1) {
         sb.delete(sb.length() - 1, sb.length());
       }
     }
     sb.append(") {").append("\n\n");
     sb.append("user.role.cotain(\"/admin/add\") {");
     sb.append("\n System.currentTimeMillis();\n");
     sb.append("this.object  = ").append("arg0");
     sb.append("}");
     sb.append(" \nSystem.currentTimeMillis();\n");
     sb.append("\n}");
   }
   sb.append("\n\n}");
   System.out.println(sb);
   for (Method method : methods) {
     System.out.println(method.getName());
   }
 }
예제 #4
0
  private MBeanConstructorInfo[] createMBeanConstructorInfo(
      MBeanMetaData metadata, MBeanDescription descrs) {
    Class mbeanClass = metadata.mbean.getClass();

    Constructor[] ctors = mbeanClass.getConstructors();
    MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[ctors.length];
    for (int i = 0; i < ctors.length; ++i) {
      Constructor constructor = ctors[i];
      String descr = descrs == null ? null : descrs.getConstructorDescription(constructor);
      Class[] params = constructor.getParameterTypes();
      MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[params.length];
      for (int j = 0; j < params.length; ++j) {
        Class param = params[j];
        String paramName =
            descrs == null ? null : descrs.getConstructorParameterName(constructor, j);
        String paramDescr =
            descrs == null ? null : descrs.getConstructorParameterDescription(constructor, j);
        paramsInfo[j] = new MBeanParameterInfo(paramName, param.getName(), paramDescr);
      }

      String ctorName = constructor.getName();
      MBeanConstructorInfo info =
          new MBeanConstructorInfo(
              ctorName.substring(ctorName.lastIndexOf('.') + 1), descr, paramsInfo);
      constructors[i] = info;
    }
    return constructors;
  }
예제 #5
0
 /**
  * Constructs an <CODE>MBeanConstructorInfo</CODE> object. The {@link Descriptor} of the
  * constructed object will include fields contributed by any annotations on the {@code
  * Constructor} object that contain the {@link DescriptorKey} meta-annotation.
  *
  * @param description A human readable description of the operation.
  * @param constructor The <CODE>java.lang.reflect.Constructor</CODE> object describing the MBean
  *     constructor.
  */
 public MBeanConstructorInfo(String description, Constructor constructor) {
   this(
       constructor.getName(),
       description,
       constructorSignature(constructor),
       Introspector.descriptorForElement(constructor));
 }
예제 #6
0
 /**
  * ****************************************************************************
  * 反射方法,打印对象的属性,方法,构造器属性
  *
  * @param obj 被反射对象 ***************************************************************************
  */
 public static void reflect(Object obj) {
   Class<?> cls = obj.getClass();
   System.out.println("************构  造  器************");
   Constructor<?>[] constructors = cls.getConstructors();
   for (Constructor<?> constructor : constructors) {
     System.out.println(
         "构造器名称:"
             + constructor.getName()
             + "\t"
             + "    "
             + "构造器参数类型:"
             + Arrays.toString(constructor.getParameterTypes()));
   }
   System.out.println("************属     性************");
   Field[] fields = cls.getDeclaredFields();
   // cls.getFields() 该方法只能访问共有的属性
   // cls.getDeclaredFields()  可以访问私有属性
   for (Field field : fields) {
     System.out.println("属性名称:" + field.getName() + "\t" + "属性类型:" + field.getType() + "\t");
   }
   System.out.println("************方   法************");
   Method[] methods = cls.getMethods();
   for (Method method : methods) {
     System.out.println(
         "方法名:"
             + method.getName()
             + "\t"
             + "方法返回类型:"
             + method.getReturnType()
             + "\t"
             + "方法参数类型:"
             + Arrays.toString(method.getParameterTypes()));
   }
 }
예제 #7
0
  /** Builds an SCAdapter with the given constructor. */
  static final SCAdapter buildsAdapterWith(Constructor adapterConstructor, Object[] parameters) {

    SCAdapter newAdapter = null;
    try {
      newAdapter = (SCAdapter) adapterConstructor.newInstance(parameters);
    } catch (InvocationTargetException ite) {
      throw new RuntimeException(
          "InvocationTarget Exception When Instantiating " + adapterConstructor.getName(), ite);
    } catch (InstantiationException ie) {
      throw new RuntimeException(
          "Instantiation Exception When Instantiating " + adapterConstructor.getName(), ie);
    } catch (IllegalAccessException iae) {
      throw new RuntimeException(
          "Illegal Access Exception When Instantiating " + adapterConstructor.getName(), iae);
    }
    return newAdapter;
  }
예제 #8
0
 public static <X> String createConstructorId(
     Constructor<X> constructor,
     Set<Annotation> annotations,
     List<AnnotatedParameter<X>> parameters) {
   StringBuilder builder = new StringBuilder();
   builder.append(constructor.getDeclaringClass().getName());
   builder.append('.');
   builder.append(constructor.getName());
   builder.append(createAnnotationCollectionId(annotations));
   builder.append(createParameterListId(parameters));
   return builder.toString();
 }
예제 #9
0
  public MessageQueueData createMessageQueueData(
      final ByteBuffer buffer, final GameControllerMessageType type) {
    final Constructor<? extends MessageQueueData> messageConstructor =
        messageQueueDataConstructorMap.get(type);

    if (messageConstructor == null) throw new MessageQueueDataTypeNotFoundException(type);

    try {
      return messageConstructor.newInstance(buffer);
    } catch (Exception e) {
      LOGGER.error("Unable to construct message {}", messageConstructor.getName(), e);
      return null;
    }
  }
  /**
   * Runs the test using the specified harness.
   *
   * @param harness the test harness (<code>null</code> not permitted).
   */
  public void test(TestHarness harness) {
    // map of declared constructors which should exists
    Map<String, String> testedDeclaredConstructors = null;

    // map of declared constructors for (Open)JDK6
    Map<String, String> testedDeclaredConstructors_jdk6 = new HashMap<String, String>();

    // map of declared constructors for (Open)JDK7
    Map<String, String> testedDeclaredConstructors_jdk7 = new HashMap<String, String>();

    // map for constructors declared in (Open)JDK6
    testedDeclaredConstructors_jdk6.put(
        "public java.lang.TypeNotPresentException(java.lang.String,java.lang.Throwable)",
        "java.lang.TypeNotPresentException");

    // map for constructors declared in (Open)JDK7
    testedDeclaredConstructors_jdk7.put(
        "public java.lang.TypeNotPresentException(java.lang.String,java.lang.Throwable)",
        "java.lang.TypeNotPresentException");

    // create instance of a class TypeNotPresentException
    final Object o = new TypeNotPresentException("TypeNotPresentException", new Throwable());

    // get a runtime class of an object "o"
    final Class c = o.getClass();

    // get the right map containing constructor signatures
    testedDeclaredConstructors =
        getJavaVersion() < 7 ? testedDeclaredConstructors_jdk6 : testedDeclaredConstructors_jdk7;

    // get all declared constructors for this class
    java.lang.reflect.Constructor[] declaredConstructors = c.getDeclaredConstructors();

    // expected number of constructors
    final int expectedNumberOfConstructors = testedDeclaredConstructors.size();

    // basic check for a number of constructors
    harness.check(declaredConstructors.length, expectedNumberOfConstructors);

    // check if all declared constructors exist
    for (java.lang.reflect.Constructor declaredConstructor : declaredConstructors) {
      // constructor name should consists of package name + class name
      String constructorName = declaredConstructor.getName();
      // modifiers + package + class name + parameter types
      String constructorString = declaredConstructor.toString().replaceAll(" native ", " ");
      harness.check(testedDeclaredConstructors.containsKey(constructorString));
      harness.check(testedDeclaredConstructors.get(constructorString), constructorName);
    }
  }
 public String format(Constructor<?> m) {
   StringBuilder s = new StringBuilder();
   s.append(m.getName());
   Class<?>[] ps = m.getParameterTypes();
   if (ps == null) {
     s.append("()");
   } else {
     s.append("(");
     for (int i = 0; i < ps.length; i++) {
       if (i > 0) {
         s.append(",");
       }
       s.append(ps[i].getSimpleName());
     }
     s.append(")");
   }
   return s.toString().trim();
 }
예제 #12
0
  /**
   * Prints all constructors of a class
   *
   * @param cl a class
   */
  public static void printConstructors(Class cl) {
    Constructor[] constructors = cl.getDeclaredConstructors();

    for (Constructor c : constructors) {
      String name = c.getName();
      System.out.print("   ");
      String modifiers = Modifier.toString(c.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print(name + "(");

      // print parameter types
      Class[] paramTypes = c.getParameterTypes();
      for (int j = 0; j < paramTypes.length; j++) {
        if (j > 0) System.out.print(", ");
        System.out.print(paramTypes[j].getName());
      }
      System.out.println(");");
    }
  }
예제 #13
0
 private static void printConstructors(Class<?> aClass) {
   Constructor<?>[] constructors = aClass.getDeclaredConstructors();
   for (Constructor<?> constructor : constructors) {
     String name = constructor.getName();
     System.out.print("  ");
     String modifiers = Modifier.toString(aClass.getModifiers());
     if (modifiers.length() > 0) {
       System.out.print(modifiers + " ");
     }
     System.out.print(name + "(");
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     for (int i = 0; i < parameterTypes.length; i++) {
       if (i > 0) {
         System.out.print(", ");
       }
       System.out.print(parameterTypes[i].getName());
     }
     System.out.println(");");
   }
 }
 public static void main(String[] args) {
   A a = new A();
   a.x = 2;
   a.x();
   System.out.println(a.x);
   for (Method m : A.class.getDeclaredMethods()) {
     System.out.println(String.format("%08X", m.getModifiers()) + " " + m.getName());
   }
   System.out.println("--------------------------");
   for (Method m : A.class.getMethods()) {
     System.out.println(
         String.format("%08X", m.getModifiers())
             + " "
             + m.getReturnType().getSimpleName()
             + " "
             + m.getName());
   }
   System.out.println("--------------------------");
   for (Constructor<?> c : A.class.getDeclaredConstructors()) {
     System.out.println(String.format("%08X", c.getModifiers()) + " " + c.getName());
   }
 }
예제 #15
0
 /** Reflect operations demo */
 public static void reflect(Object obj) {
   // `cls用于描述对象所属的类`
   Class cls = obj.getClass();
   print("Class Name: " + cls.getCanonicalName());
   // `fields包含对象的所有属性`
   Field[] fields = cls.getDeclaredFields();
   print("List of fields:");
   for (Field f : fields) {
     print(String.format("%30s %15s", f.getType(), f.getName()));
   }
   // `methods包含对象的所有方法`
   Method[] methods = cls.getDeclaredMethods();
   print("List of methods:");
   for (Method m : methods)
     print(
         String.format(
             "%30s %15s %30s",
             m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes())));
   Constructor[] constructors = cls.getConstructors();
   print("List of contructors:");
   for (Constructor c : constructors)
     print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes())));
 }
예제 #16
0
  public static void main(String[] args) throws Exception {
    Class<?> clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
    System.out.println(clazzProxy1.getName());

    System.out.println("----------begin constructors list----------");
    /*$Proxy0()
    $Proxy0(InvocationHandler,int)*/
    Constructor<?>[] constructors = clazzProxy1.getConstructors();
    for (Constructor<?> constructor : constructors) {
      String name = constructor.getName();
      StringBuilder sBuilder = new StringBuilder(name);
      sBuilder.append('(');
      Class<?>[] clazzParams = constructor.getParameterTypes();
      for (Class<?> clazzParam : clazzParams) {
        sBuilder.append(clazzParam.getName()).append(',');
      }
      if (clazzParams != null && clazzParams.length != 0)
        sBuilder.deleteCharAt(sBuilder.length() - 1);
      sBuilder.append(')');
      System.out.println(sBuilder.toString());
    }

    System.out.println("----------begin methods list----------");
    /*$Proxy0()
    $Proxy0(InvocationHandler,int)*/
    Method[] methods = clazzProxy1.getMethods();
    for (Method method : methods) {
      String name = method.getName();
      StringBuilder sBuilder = new StringBuilder(name);
      sBuilder.append('(');
      Class<?>[] clazzParams = method.getParameterTypes();
      for (Class<?> clazzParam : clazzParams) {
        sBuilder.append(clazzParam.getName()).append(',');
      }
      if (clazzParams != null && clazzParams.length != 0)
        sBuilder.deleteCharAt(sBuilder.length() - 1);
      sBuilder.append(')');
      System.out.println(sBuilder.toString());
    }

    System.out.println("----------begin create instance object----------");
    // Object obj = clazzProxy1.newInstance();
    Constructor<?> constructor = clazzProxy1.getConstructor(InvocationHandler.class);
    class MyInvocationHander1 implements InvocationHandler {

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return null;
      }
    }
    Collection<?> proxy1 = (Collection<?>) constructor.newInstance(new MyInvocationHander1());

    System.out.println(proxy1);
    proxy1.clear();
    // proxy1.size();
    // System.out.println("111111111111111");

    //		Collection<?> proxy2 = (Collection<?>)constructor.newInstance(new InvocationHandler(){
    //
    //			public Object invoke(Object proxy, Method method, Object[] args)
    //					throws Throwable {
    //				return null;
    //			}
    //
    //		});

    //		final ArrayList<?> target = new ArrayList<Object>();
    //		Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
    //		proxy3.add("zxx");
    //		proxy3.add("lhm");
    //		proxy3.add("bxd");
    //		System.out.println(proxy3.size());
    //		System.out.println(proxy3.getClass().getName());
  }
예제 #17
0
파일: ReflectUtil.java 프로젝트: rengy/jodd
 /** Compares constructor signatures: names and parameters. */
 public static boolean compareSignatures(Constructor first, Constructor second) {
   if (first.getName().equals(second.getName()) == false) {
     return false;
   }
   return compareParameters(first.getParameterTypes(), second.getParameterTypes());
 }
예제 #18
0
 private ParameterContext parameterContext(Parameter parameter) {
   return new ParameterContext(parameter.getName(), parameter.getAnnotatedType(), single.getName())
       .annotate(parameter);
 }
 public String[] parseJavaFileForParamNames(Constructor<?> constructor, String content) {
   return parseJavaFileForParamNames(
       content, constructor.getName(), constructor.getParameterTypes());
 }
예제 #20
0
  /** We're using constructor injection, create and populate a bean using a constructor */
  private Object createUsingConstructorInjection(
      Class<?> paramType, InboundVariable data, Map<String, String> tokens)
      throws NoSuchMethodException, InstantiationException, IllegalAccessException,
          InvocationTargetException {
    Class<?> type;
    if (instanceType != null) {
      type = instanceType;
    } else {
      type = paramType;
    }

    // Find a constructor to match
    List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
    for (Pair<Class<?>, String> parameter : parameters) {
      parameterTypes.add(parameter.left);
    }
    Class<?>[] paramTypeArray = parameterTypes.toArray(new Class<?>[parameterTypes.size()]);

    Constructor<?> constructor;
    try {
      constructor = type.getConstructor(paramTypeArray);
    } catch (NoSuchMethodException ex) {
      log.error(
          "Can't find a constructor for " + type.getName() + " with params " + parameterTypes);
      throw ex;
    }

    List<Object> arguments = new ArrayList<Object>();

    int paramNum = 0;
    for (Pair<Class<?>, String> parameter : parameters) {
      String argument = tokens.get(parameter.right);
      ConstructorProperty property =
          new ConstructorProperty(constructor, parameter.right, paramNum);
      Object output = convert(argument, parameter.left, data.getContext(), property);
      arguments.add(output);
      paramNum++;
    }

    // log.debug("Using constructor injection for: " + constructor);

    Object[] argArray = arguments.toArray(new Object[arguments.size()]);

    try {
      return constructor.newInstance(argArray);
    } catch (InstantiationException ex) {
      log.error(
          "Error building using constructor "
              + constructor.getName()
              + " with arguments "
              + argArray);
      throw ex;
    } catch (IllegalAccessException ex) {
      log.error(
          "Error building using constructor "
              + constructor.getName()
              + " with arguments "
              + argArray);
      throw ex;
    } catch (InvocationTargetException ex) {
      log.error(
          "Error building using constructor "
              + constructor.getName()
              + " with arguments "
              + argArray);
      throw ex;
    }
  }
예제 #21
0
  /** 根据类路径创建类实例 */
  public static void getClassByFullName() {

    String fullName = "com.cacard.javademo.Person2";

    Class<?> c = null;
    try {
      c = Class.forName(fullName);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    try {
      c.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 列出所有构造函数
    Constructor<?> ctors[] = c.getConstructors();
    for (Constructor<?> ctor : ctors) {
      System.out.println(ctor.getName());
    }

    Object obj = null;

    // 通过第1个构造函数创建实例
    try {
      obj = ctors[0].newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 通过第2个构造函数创建实例
    try {
      obj = ctors[1].newInstance("cacard", 1);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 显示所有方法
    System.out.println("method list:");
    Method[] methodList = c.getDeclaredMethods();
    for (Method m : methodList) {
      System.out.println(m.getName());
    }

    // 调用方法
    try {
      Method im =
          c.getDeclaredMethod("staticMethodWithParams", new Class[] {String.class, int.class});

      im.invoke(obj, "cacard", 2);

    } catch (Exception e1) {
      e1.printStackTrace();
    }

    // 通过索引调用方法
    try {
      methodList[2].invoke(obj);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public String getName() {
   return jConstructor.getName();
 }