List of usage examples for org.objectweb.asm Type getConstructorDescriptor
public static String getConstructorDescriptor(final Constructor<?> constructor)
From source file:ca.weblite.netbeans.mirah.lexer.ClassQuery.java
/** * Returns a list containing one parameter name for each argument accepted * by the given constructor. If the class was compiled with debugging * symbols, the parameter names will match those provided in the Java source * code. Otherwise, a generic "arg" parameter name is generated ("arg0" for * the first argument, "arg1" for the second...). * * This method relies on the constructor's class loader to locate the * bytecode resource that defined its class. * * @param constructor/* ww w.j av a 2 s .c om*/ * @return * @throws IOException */ public List<String> getParameterNames(Constructor<?> constructor) throws IOException { //Class<?> declaringClass = constructor.getDeclaringClass(); Class declaringClass = cls; ClassLoader declaringClassLoader = declaringClass.getClassLoader(); Type declaringType = Type.getType(declaringClass); String constructorDescriptor = Type.getConstructorDescriptor(constructor); String url = declaringType.getInternalName() + ".class"; InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url); if (classFileInputStream == null) { throw new IllegalArgumentException( "The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: " + url + ")"); } ClassNode classNode; try { classNode = new ClassNode(); ClassReader classReader = new ClassReader(classFileInputStream); classReader.accept(classNode, 0); } finally { classFileInputStream.close(); } @SuppressWarnings("unchecked") List<MethodNode> methods = classNode.methods; for (MethodNode method : methods) { if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) { Type[] argumentTypes = Type.getArgumentTypes(method.desc); List<String> parameterNames = new ArrayList<String>(argumentTypes.length); @SuppressWarnings("unchecked") List<LocalVariableNode> localVariables = method.localVariables; for (int i = 0; i < argumentTypes.length; i++) { // The first local variable actually represents the "this" object parameterNames.add(localVariables.get(i + 1).name); } return parameterNames; } } return null; }
From source file:co.paralleluniverse.common.util.ExtendedStackTrace.java
License:Open Source License
protected static final String getDescriptor(Member m) { if (m instanceof Constructor) return Type.getConstructorDescriptor((Constructor) m); return Type.getMethodDescriptor((Method) m); }
From source file:com.alibaba.hotswap.processor.jdk.helper.MethodReflectHelper.java
License:Open Source License
public static Constructor<?>[] getDeclaredConstructors0(Class<?> clazz, boolean publicOnly) { String name = clazz.getName(); ClassMeta classMeta = HotswapRuntime.getClassMeta(name); Constructor<?>[] constructors = null; if (publicOnly) { constructors = classMeta.vClass.getConstructors(); } else {/*w ww. j ava2 s . c o m*/ constructors = classMeta.vClass.getDeclaredConstructors(); } try { List<Constructor<?>> constructorList = new ArrayList<Constructor<?>>(); // Remove constructor which has been deleted Field clazzField = Constructor.class.getDeclaredField("clazz"); clazzField.setAccessible(true); for (Constructor<?> c : constructors) { String mk = HotswapMethodUtil.getMethodKey(HotswapConstants.INIT, Type.getConstructorDescriptor(c)); MethodMeta mm = classMeta.initMetas.get(mk); if (!mm.isDeleted(classMeta.loadedIndex)) { clazzField.set(c, clazz); constructorList.add(c); } } Method getDeclaredConstructors0Method = Class.class.getDeclaredMethod("getDeclaredConstructors0", boolean.class); getDeclaredConstructors0Method.setAccessible(true); Constructor<?>[] tranformConstructors = (Constructor[]) getDeclaredConstructors0Method.invoke(clazz, publicOnly); for (Constructor<?> c : tranformConstructors) { if (isUniformConstructorArgsType(c.getParameterTypes())) { constructorList.add(c); } } return constructorList.toArray(new Constructor[] {}); } catch (Exception e) { e.printStackTrace(); } // unreached return new Constructor<?>[0]; }
From source file:com.sixrr.metrics.profile.instanceHolder.MetricInstanceHolder.java
License:Apache License
private void loadMetricsFromProviders() { for (MetricProvider provider : MetricProvider.EXTENSION_POINT_NAME.getExtensions()) { final List<Class<? extends Metric>> classesForProvider = provider.getMetricClasses(); for (Class<? extends Metric> aClass : classesForProvider) { try { myMetricInstances.put(aClass.getName(), aClass.newInstance()); } catch (InstantiationException e) { MetricInstanceHolder.LOGGER.error(e); } catch (IllegalAccessException e) { MetricInstanceHolder.LOGGER.error(e); }/* w w w . ja va2 s . c om*/ } } for (Metric metric : Metric.EP_NAME.getExtensions()) { myMetricInstances.put(metric.getClass().getName(), metric); } // add some magic // in Profiles it stored by ClassName. Line Of code is can be handle without new metrics, need only extends LinesOfCodeProjectMetric with // new name for (LineOfCodeFileTypeProviderEP ep : LineOfCodeFileTypeProviderEP.EP_NAME.getExtensions()) { FileType fileTypeByFileName = FileTypeRegistry.getInstance().findFileTypeByName(ep.fileType); if (fileTypeByFileName == null) { LOGGER.error("File type is unknown: " + ep.fileType); fileTypeByFileName = PlainTextFileType.INSTANCE; } String lineOfCodeClass = Type.getInternalName(LinesOfCodeProjectMetric.class); String className = lineOfCodeClass + "$" + ep.fileType; ClassWriter writer = new ClassWriter(Opcodes.F_FULL); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, lineOfCodeClass, null); String desc = Type.getConstructorDescriptor(LinesOfCodeProjectMetric.class.getConstructors()[0]); MethodVisitor methodVisitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, null, null); methodVisitor.visitMaxs(2, 2); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, lineOfCodeClass, "<init>", desc); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitEnd(); writer.visitEnd(); Class<?> aClass = defineClass(className.replace("/", "."), writer.toByteArray()); try { myMetricInstances.put(aClass.getName(), (Metric) aClass.getConstructors()[0].newInstance(fileTypeByFileName)); } catch (InstantiationException e) { LOGGER.error(e); } catch (IllegalAccessException e) { LOGGER.error(e); } catch (InvocationTargetException e) { LOGGER.error(e); } } }
From source file:de.zib.sfs.instrument.AbstractSfsAdapter.java
License:BSD License
protected <InstrumentedType, CallbackType> AbstractSfsAdapter(ClassVisitor cv, Class<InstrumentedType> instrumentedTypeClass, Class<CallbackType> callbackTypeClass, String methodPrefix, Set<OperationCategory> skip) { super(Opcodes.ASM5, cv); this.methodPrefix = methodPrefix; this.instrumentedTypeInternalName = Type.getInternalName(instrumentedTypeClass); this.callbackTypeInternalName = Type.getInternalName(callbackTypeClass); this.callbackTypeDescriptor = Type.getDescriptor(callbackTypeClass); try {//from w w w .j av a 2 s.c o m this.callbackTypeConstructorDescriptor = Type .getConstructorDescriptor(callbackTypeClass.getConstructor(instrumentedTypeClass)); } catch (Exception e) { throw new IllegalArgumentException( "Constructor of " + this.callbackTypeInternalName + " is not accessible.", e); } this.systemInternalName = Type.getInternalName(System.class); this.nanoTimeDescriptor = Type.getMethodDescriptor(Type.LONG_TYPE); this.skip = skip; }
From source file:de.zib.sfs.instrument.AbstractSfsAdapter.java
License:BSD License
protected <CallbackType> AbstractSfsAdapter(ClassVisitor cv, String instrumentedTypeInternalName, Class<CallbackType> callbackTypeClass, String methodPrefix, Set<OperationCategory> skip) { super(Opcodes.ASM5, cv); this.methodPrefix = methodPrefix; this.instrumentedTypeInternalName = instrumentedTypeInternalName; this.callbackTypeInternalName = Type.getInternalName(callbackTypeClass); this.callbackTypeDescriptor = Type.getDescriptor(callbackTypeClass); try {//from ww w. j av a 2 s . c o m this.callbackTypeConstructorDescriptor = Type .getConstructorDescriptor(callbackTypeClass.getConstructor()); } catch (Exception e) { throw new IllegalArgumentException( "No-arg constructor of " + this.callbackTypeInternalName + " is not accessible.", e); } this.systemInternalName = Type.getInternalName(System.class); this.nanoTimeDescriptor = Type.getMethodDescriptor(Type.LONG_TYPE); this.skip = skip; }
From source file:de.zib.sfs.instrument.ZipFileAdapter.java
License:BSD License
protected ZipFileAdapter(ClassVisitor cv, String methodPrefix, Set<OperationCategory> skip) { super(Opcodes.ASM5, cv); this.methodPrefix = methodPrefix; Constructor<ZipFile> constructor; try {//from ww w . j a v a 2s. c o m constructor = ZipFile.class.getConstructor(File.class, Integer.TYPE, Charset.class); this.constructorDescriptor = Type.getConstructorDescriptor(constructor); } catch (Exception e) { throw new RuntimeException("Could not access constructor", e); } this.skip = skip; }
From source file:devtools.cdbg.debuglets.java.codegen.JniProxyCodeGen.java
License:Open Source License
public JniProxyCodeGen(File path, Class<?> cls, Config.ProxyClass config) { this.path = path; this.cls = cls; this.classConfig = config; fileNameClass = cls.getName().replace('.', '_').replace('$', '_').replaceFirst("^java_math_", "") .replaceFirst("^java_lang_", "").replaceFirst("^java_io_", "") .replaceFirst("^java_util_logging_", "jul_").replaceFirst("^java_util_", "ju_") .replaceFirst("^com_google_api_client_util_", "api_client_") .replaceFirst("^com_google_devtools_cdbg_debuglets_java_", "").toLowerCase(); Constructor<?>[] clsConstructors = cls.getDeclaredConstructors(); Method[] clsMethods = cls.getDeclaredMethods(); // Sort list of methods to ensure consistent generated code (Class returns elements // in no particular order). Comparator<Object> methodComparator = new Comparator<Object>() { @Override//from w w w. j av a 2 s .c o m public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; Arrays.sort(clsConstructors, methodComparator); Arrays.sort(clsMethods, methodComparator); constructors = new ArrayList<>(); methods = new ArrayList<>(); for (Config.ProxyMethod methodConfig : config.getMethods()) { boolean found = false; if (methodConfig.getMethodName().equals("<init>")) { for (Constructor<?> constructor : clsConstructors) { if ((methodConfig.getMethodSignature() != null) && !Type.getConstructorDescriptor(constructor) .equals(methodConfig.getMethodSignature())) { continue; } constructors.add(new ProxyConstructor(methodConfig.isSubclassConstructor(), constructor, constructors.size())); found = true; } } else { for (Method method : clsMethods) { if (!method.getName().equals(methodConfig.getMethodName())) { continue; } if ((methodConfig.getMethodSignature() != null) && !Type.getMethodDescriptor(method).equals(methodConfig.getMethodSignature())) { continue; } methods.add(new ProxyMethod(method, methods.size())); found = true; } } if (!found) { throw new RuntimeException(String.format("Method %s (signature: %s) not found in class %s", methodConfig.getMethodName(), (methodConfig.getMethodSignature() != null) ? methodConfig.getMethodSignature() : "any", cls.getName())); } } codeGenConfig = new Configuration(Configuration.VERSION_2_3_22); codeGenConfig.setClassForTemplateLoading(getClass(), ""); codeGenConfig.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22)); }
From source file:fr.insalyon.citi.golo.runtime.adapters.JavaBytecodeAdapterGenerator.java
License:Apache License
private void makeConstructors(ClassWriter classWriter, AdapterDefinition adapterDefinition) { try {/* w ww . j av a 2s. c o m*/ Class<?> parentClass = Class.forName(adapterDefinition.getParent(), true, adapterDefinition.getClassLoader()); for (Constructor constructor : parentClass.getDeclaredConstructors()) { if (Modifier.isPublic(constructor.getModifiers()) || Modifier.isProtected(constructor.getModifiers())) { Class[] parameterTypes = constructor.getParameterTypes(); Type[] adapterParameterTypes = new Type[parameterTypes.length + 1]; adapterParameterTypes[0] = Type.getType(AdapterDefinition.class); for (int i = 1; i < adapterParameterTypes.length; i++) { adapterParameterTypes[i] = Type.getType(parameterTypes[i - 1]); } String descriptor = Type.getMethodDescriptor(Type.VOID_TYPE, adapterParameterTypes); MethodVisitor methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", descriptor, null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitVarInsn(ALOAD, 1); methodVisitor.visitFieldInsn(PUTFIELD, jvmType(adapterDefinition.getName()), DEFINITION_FIELD, "Lfr/insalyon/citi/golo/runtime/adapters/AdapterDefinition;"); methodVisitor.visitVarInsn(ALOAD, 0); int argIndex = 2; for (Class parameterType : parameterTypes) { argIndex = loadArgument(methodVisitor, parameterType, argIndex); } methodVisitor.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(parentClass), "<init>", Type.getConstructorDescriptor(constructor)); methodVisitor.visitInsn(RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
From source file:nova.core.wrapper.mc.forge.v17.asm.lib.ComponentInjector.java
License:Open Source License
private Class<? extends T> construct(List<Class<? extends Component>> components) { // Map components to specified wrapped interfaces Map<Class<?>, Class<? extends Component>> intfComponentMap = new HashMap<>(); for (Class<? extends Component> component : components) { for (Passthrough pt : component.getAnnotationsByType(Passthrough.class)) { Class<?> intf;/*from w w w.ja v a 2 s . co m*/ try { intf = Class.forName(pt.value()); } catch (ClassNotFoundException exec) { throw new ClassLoaderUtil.ClassLoaderException( "Invalid passthrough \"%s\" on component %s, the specified interface doesn't exist.", pt.value(), component); } if (!intf.isAssignableFrom(component)) { throw new ClassLoaderUtil.ClassLoaderException( "Invalid passthrough \"%s\" on component %s, the specified interface isn't implemented.", pt.value(), component); } if (intfComponentMap.containsKey(intf)) { throw new ClassLoaderUtil.ClassLoaderException( "Duplicate Passthrough interface found: %s (%s, %s)", pt.value(), component, intfComponentMap.get(intf)); } intfComponentMap.put(intf, component); } } // Create new ClassNode from cached bytes ClassNode clazzNode = new ClassNode(); String name = Type.getInternalName(baseClazz); String classname = name + "_$$_NOVA_" + cache.size(); // Inject block field clazzNode.visit(V1_8, ACC_PUBLIC | ACC_SUPER, classname, null, name, intfComponentMap.keySet().stream().map(Type::getInternalName).toArray(s -> new String[s])); clazzNode.visitField(ACC_PRIVATE | ACC_FINAL, "$$_provider", Type.getDescriptor(ComponentProvider.class), null, null).visitEnd(); // Add constructors for (Constructor<?> constructor : baseClazz.getConstructors()) { int mod = constructor.getModifiers(); String descr = Type.getConstructorDescriptor(constructor); if (Modifier.isFinal(mod) || Modifier.isPrivate(mod)) { continue; } MethodVisitor mv = clazzNode.visitMethod(mod, "<init>", descr, null, ASMHelper.getExceptionTypes(constructor)); // Call super constructor mv.visitCode(); // load this mv.visitVarInsn(ALOAD, 0); Class<?>[] parameters = constructor.getParameterTypes(); for (int i = 0; i < constructor.getParameterCount(); i++) { // variables mv.visitVarInsn(Type.getType(parameters[i]).getOpcode(ILOAD), i + 1); } mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(baseClazz), "<init>", descr, false); // return mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } // Add methods for (Class<?> intf : intfComponentMap.keySet()) { // Create class constant Type clazzConst = Type.getType(intf.getClass()); for (Method m : intf.getMethods()) { boolean isVoid = m.getReturnType() == null; String descr = Type.getMethodDescriptor(m); MethodVisitor mv = clazzNode.visitMethod(ACC_PUBLIC, m.getName(), descr, null, ASMHelper.getExceptionTypes(m)); mv.visitCode(); // load block instance mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classname, "$$_provider", Type.getDescriptor(ComponentProvider.class)); mv.visitLdcInsn(clazzConst); // load component instance mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(ComponentProvider.class), "get", Type.getMethodDescriptor(Type.getType(Component.class), Type.getType(Class.class)), false); // add parameters Class<?>[] parameters = m.getParameterTypes(); for (int i = 0; i < m.getParameterCount(); i++) { mv.visitVarInsn(Type.getType(parameters[i]).getOpcode(ILOAD), i + 1); } // invoke mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(intf), m.getName(), descr, true); mv.visitInsn(isVoid ? RETURN : Type.getType(m.getReturnType()).getOpcode(IRETURN)); mv.visitMaxs(0, 0); mv.visitEnd(); } } clazzNode.visitEnd(); return ASMHelper.defineClass(clazzNode, ClassWriter.COMPUTE_MAXS, baseClazz.getProtectionDomain()); }