Search in sources :

Example 11 with Constructor

use of java.lang.reflect.Constructor in project groovy by apache.

the class BindPathSnooper method createBinding.

public FullBinding createBinding(SourceBinding source, TargetBinding target) {
    if (source != this) {
        throw new RuntimeException("Source binding must the Trigger Binding as well");
    }
    final BindPathSnooper delegate = new BindPathSnooper();
    try {
        // create our own local copy of the closure
        final Class closureClass = closure.getClass();
        // do in privileged block since we may be looking at private stuff
        Closure closureLocalCopy = java.security.AccessController.doPrivileged(new PrivilegedAction<Closure>() {

            public Closure run() {
                // assume closures have only 1 constructor, of the form (Object, Reference*)
                Constructor constructor = closureClass.getConstructors()[0];
                int paramCount = constructor.getParameterTypes().length;
                Object[] args = new Object[paramCount];
                args[0] = delegate;
                for (int i = 1; i < paramCount; i++) {
                    args[i] = new Reference(new BindPathSnooper());
                }
                try {
                    boolean acc = constructor.isAccessible();
                    constructor.setAccessible(true);
                    Closure localCopy = (Closure) constructor.newInstance(args);
                    if (!acc) {
                        constructor.setAccessible(false);
                    }
                    localCopy.setResolveStrategy(Closure.DELEGATE_ONLY);
                    for (Field f : closureClass.getDeclaredFields()) {
                        acc = f.isAccessible();
                        f.setAccessible(true);
                        if (f.getType() == Reference.class) {
                            delegate.fields.put(f.getName(), (BindPathSnooper) ((Reference) f.get(localCopy)).get());
                        }
                        if (!acc) {
                            f.setAccessible(false);
                        }
                    }
                    return localCopy;
                } catch (Exception e) {
                    throw new RuntimeException("Error snooping closure", e);
                }
            }
        });
        try {
            closureLocalCopy.call();
        } catch (DeadEndException e) {
            // we want this exception exposed.
            throw e;
        } catch (Exception e) {
        //LOGME
        // ignore it, likely failing because we are faking out properties
        // such as a call to Math.min(int, BindPathSnooper)
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("A closure expression binding could not be created because of " + e.getClass().getName() + ":\n\t" + e.getMessage());
    }
    List<BindPath> rootPaths = new ArrayList<BindPath>();
    for (Map.Entry<String, BindPathSnooper> entry : delegate.fields.entrySet()) {
        BindPath bp = createBindPath(entry.getKey(), entry.getValue());
        bp.currentObject = closure;
        rootPaths.add(bp);
    }
    PropertyPathFullBinding fb = new PropertyPathFullBinding();
    fb.setSourceBinding(new ClosureSourceBinding(closure));
    fb.setTargetBinding(target);
    fb.bindPaths = rootPaths.toArray(new BindPath[rootPaths.size()]);
    return fb;
}
Also used : Closure(groovy.lang.Closure) Constructor(java.lang.reflect.Constructor) Reference(groovy.lang.Reference) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 12 with Constructor

use of java.lang.reflect.Constructor in project hadoop by apache.

the class TestErasureCoderBase method createEncoder.

/**
   * Create the raw erasure encoder to test
   * @return
   */
protected ErasureCoder createEncoder() {
    ErasureCoder encoder;
    try {
        ErasureCoderOptions options = new ErasureCoderOptions(numDataUnits, numParityUnits, allowChangeInputs, allowDump);
        Constructor<? extends ErasureCoder> constructor = (Constructor<? extends ErasureCoder>) encoderClass.getConstructor(ErasureCoderOptions.class);
        encoder = constructor.newInstance(options);
    } catch (Exception e) {
        throw new RuntimeException("Failed to create encoder", e);
    }
    encoder.setConf(getConf());
    return encoder;
}
Also used : ErasureCoderOptions(org.apache.hadoop.io.erasurecode.ErasureCoderOptions) Constructor(java.lang.reflect.Constructor)

Example 13 with Constructor

use of java.lang.reflect.Constructor in project android_frameworks_base by ParanoidAndroid.

the class ConnectivityService method makeWimaxStateTracker.

/**
     * Loads external WiMAX library and registers as system service, returning a
     * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
     * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
     */
private static NetworkStateTracker makeWimaxStateTracker(Context context, Handler trackerHandler) {
    // Initialize Wimax
    DexClassLoader wimaxClassLoader;
    Class wimaxStateTrackerClass = null;
    Class wimaxServiceClass = null;
    Class wimaxManagerClass;
    String wimaxJarLocation;
    String wimaxLibLocation;
    String wimaxManagerClassName;
    String wimaxServiceClassName;
    String wimaxStateTrackerClassName;
    NetworkStateTracker wimaxStateTracker = null;
    boolean isWimaxEnabled = context.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
    if (isWimaxEnabled) {
        try {
            wimaxJarLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceJarLocation);
            wimaxLibLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxNativeLibLocation);
            wimaxManagerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxManagerClassname);
            wimaxServiceClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceClassname);
            wimaxStateTrackerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxStateTrackerClassname);
            if (DBG)
                log("wimaxJarLocation: " + wimaxJarLocation);
            wimaxClassLoader = new DexClassLoader(wimaxJarLocation, new ContextWrapper(context).getCacheDir().getAbsolutePath(), wimaxLibLocation, ClassLoader.getSystemClassLoader());
            try {
                wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
                wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
                wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
            } catch (ClassNotFoundException ex) {
                loge("Exception finding Wimax classes: " + ex.toString());
                return null;
            }
        } catch (Resources.NotFoundException ex) {
            loge("Wimax Resources does not exist!!! ");
            return null;
        }
        try {
            if (DBG)
                log("Starting Wimax Service... ");
            Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor(new Class[] { Context.class, Handler.class });
            wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(context, trackerHandler);
            Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor(new Class[] { Context.class, wimaxStateTrackerClass });
            wmxSrvConst.setAccessible(true);
            IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(context, wimaxStateTracker);
            wmxSrvConst.setAccessible(false);
            ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
        } catch (Exception ex) {
            loge("Exception creating Wimax classes: " + ex.toString());
            return null;
        }
    } else {
        loge("Wimax is not enabled or not added to the network attributes!!! ");
        return null;
    }
    return wimaxStateTracker;
}
Also used : IBinder(android.os.IBinder) Constructor(java.lang.reflect.Constructor) DexClassLoader(dalvik.system.DexClassLoader) Resources(android.content.res.Resources) NetworkStateTracker(android.net.NetworkStateTracker) ContextWrapper(android.content.ContextWrapper) RemoteException(android.os.RemoteException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) ActivityNotFoundException(android.content.ActivityNotFoundException)

Example 14 with Constructor

use of java.lang.reflect.Constructor in project android_frameworks_base by ParanoidAndroid.

the class TestMethod method instantiateTest.

@SuppressWarnings("unchecked")
private TestCase instantiateTest(Class testCaseClass, String testName) throws InvocationTargetException, IllegalAccessException, InstantiationException {
    Constructor[] constructors = testCaseClass.getConstructors();
    if (constructors.length == 0) {
        return instantiateTest(testCaseClass.getSuperclass(), testName);
    } else {
        for (Constructor constructor : constructors) {
            Class[] params = constructor.getParameterTypes();
            if (noargsConstructor(params)) {
                TestCase test = ((Constructor<? extends TestCase>) constructor).newInstance();
                // JUnit will run just the one test if you call
                // {@link TestCase#setName(String)}
                test.setName(testName);
                return test;
            } else if (singleStringConstructor(params)) {
                return ((Constructor<? extends TestCase>) constructor).newInstance(testName);
            }
        }
    }
    throw new RuntimeException("Unable to locate a constructor for " + testCaseClass.getName());
}
Also used : TestCase(junit.framework.TestCase) Constructor(java.lang.reflect.Constructor)

Example 15 with Constructor

use of java.lang.reflect.Constructor in project android_frameworks_base by ParanoidAndroid.

the class DelegateClassAdapterTest method testDelegateInner.

@Test
public void testDelegateInner() throws Throwable {
    // We'll delegate the "get" method of both the inner and outer class.
    HashSet<String> delegateMethods = new HashSet<String>();
    delegateMethods.add("get");
    delegateMethods.add("privateMethod");
    // Generate the delegate for the outer class.
    ClassWriter cwOuter = new ClassWriter(0);
    String outerClassName = OUTER_CLASS_NAME.replace('.', '/');
    DelegateClassAdapter cvOuter = new DelegateClassAdapter(mLog, cwOuter, outerClassName, delegateMethods);
    ClassReader cr = new ClassReader(OUTER_CLASS_NAME);
    cr.accept(cvOuter, 0);
    // Generate the delegate for the inner class.
    ClassWriter cwInner = new ClassWriter(0);
    String innerClassName = INNER_CLASS_NAME.replace('.', '/');
    DelegateClassAdapter cvInner = new DelegateClassAdapter(mLog, cwInner, innerClassName, delegateMethods);
    cr = new ClassReader(INNER_CLASS_NAME);
    cr.accept(cvInner, 0);
    // Load the generated classes in a different class loader and try them
    ClassLoader2 cl2 = null;
    try {
        cl2 = new ClassLoader2() {

            @Override
            public void testModifiedInstance() throws Exception {
                // Check the outer class
                Class<?> outerClazz2 = loadClass(OUTER_CLASS_NAME);
                Object o2 = outerClazz2.newInstance();
                assertNotNull(o2);
                // The original Outer.get returns 1+10+20,
                // but the delegate makes it return 4+10+20
                assertEquals(4 + 10 + 20, callGet(o2, 10, 20));
                assertEquals(1 + 10 + 20, callGet_Original(o2, 10, 20));
                // The original Outer has a private method that is
                // delegated. We should be able to call both the delegate
                // and the original (which is now public).
                assertEquals("outerPrivateMethod", callMethod(o2, "privateMethod_Original", false));
                // The original method is private, so by default we can't access it
                boolean gotIllegalAccessException = false;
                try {
                    callMethod(o2, "privateMethod", false);
                } catch (IllegalAccessException e) {
                    gotIllegalAccessException = true;
                }
                assertTrue(gotIllegalAccessException);
                // Try again, but now making it accessible
                assertEquals("outerPrivate_Delegate", callMethod(o2, "privateMethod", true));
                // Check the inner class. Since it's not a static inner class, we need
                // to use the hidden constructor that takes the outer class as first parameter.
                Class<?> innerClazz2 = loadClass(INNER_CLASS_NAME);
                Constructor<?> innerCons = innerClazz2.getConstructor(new Class<?>[] { outerClazz2 });
                Object i2 = innerCons.newInstance(new Object[] { o2 });
                assertNotNull(i2);
                // The original Inner.get returns 3+10+20,
                // but the delegate makes it return 6+10+20
                assertEquals(6 + 10 + 20, callGet(i2, 10, 20));
                assertEquals(3 + 10 + 20, callGet_Original(i2, 10, 20));
            }
        };
        cl2.add(OUTER_CLASS_NAME, cwOuter.toByteArray());
        cl2.add(INNER_CLASS_NAME, cwInner.toByteArray());
        cl2.testModifiedInstance();
    } catch (Throwable t) {
        throw dumpGeneratedClass(t, cl2);
    }
}
Also used : Constructor(java.lang.reflect.Constructor) ClassWriter(org.objectweb.asm.ClassWriter) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ClassReader(org.objectweb.asm.ClassReader) OuterClass(com.android.tools.layoutlib.create.dataclass.OuterClass) InnerClass(com.android.tools.layoutlib.create.dataclass.OuterClass.InnerClass) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

Constructor (java.lang.reflect.Constructor)1311 InvocationTargetException (java.lang.reflect.InvocationTargetException)281 Method (java.lang.reflect.Method)252 IOException (java.io.IOException)128 Field (java.lang.reflect.Field)111 ArrayList (java.util.ArrayList)106 Test (org.junit.Test)92 DOMTestDocumentBuilderFactory (org.w3c.domts.DOMTestDocumentBuilderFactory)74 JUnitTestSuiteAdapter (org.w3c.domts.JUnitTestSuiteAdapter)73 List (java.util.List)61 JAXPDOMTestDocumentBuilderFactory (org.w3c.domts.JAXPDOMTestDocumentBuilderFactory)58 Map (java.util.Map)50 Type (java.lang.reflect.Type)39 Annotation (java.lang.annotation.Annotation)38 HashMap (java.util.HashMap)38 HashSet (java.util.HashSet)31 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)31 ParameterizedType (java.lang.reflect.ParameterizedType)30 File (java.io.File)20 URL (java.net.URL)20