Example usage for java.lang Class getDeclaredConstructors

List of usage examples for java.lang Class getDeclaredConstructors

Introduction

In this page you can find the example usage for java.lang Class getDeclaredConstructors.

Prototype

@CallerSensitive
public Constructor<?>[] getDeclaredConstructors() throws SecurityException 

Source Link

Document

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

Usage

From source file:org.apache.hama.ml.ann.NeuralNetwork.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from w w  w  . j  a  va2 s  .  c  o m
public void readFields(DataInput input) throws IOException {
    // read model type
    this.modelType = WritableUtils.readString(input);
    // read learning rate
    this.learningRate = input.readDouble();
    // read model path
    this.modelPath = WritableUtils.readString(input);

    if (this.modelPath.equals("null")) {
        this.modelPath = null;
    }

    // read feature transformer
    int bytesLen = input.readInt();
    byte[] featureTransformerBytes = new byte[bytesLen];
    for (int i = 0; i < featureTransformerBytes.length; ++i) {
        featureTransformerBytes[i] = input.readByte();
    }

    Class<? extends FeatureTransformer> featureTransformerCls = (Class<? extends FeatureTransformer>) SerializationUtils
            .deserialize(featureTransformerBytes);

    Constructor[] constructors = featureTransformerCls.getDeclaredConstructors();
    Constructor constructor = constructors[0];

    try {
        this.featureTransformer = (FeatureTransformer) constructor.newInstance(new Object[] {});
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.horn.core.AbstractNeuralNetwork.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w  ww. j av a  2s .  co m
public void readFields(DataInput input) throws IOException {
    // read model type
    this.modelType = WritableUtils.readString(input);
    // read learning rate
    this.learningRate = input.readFloat();
    // read model path
    this.modelPath = WritableUtils.readString(input);

    if (this.modelPath.equals("null")) {
        this.modelPath = null;
    }

    // read feature transformer
    int bytesLen = input.readInt();
    byte[] featureTransformerBytes = new byte[bytesLen];
    for (int i = 0; i < featureTransformerBytes.length; ++i) {
        featureTransformerBytes[i] = input.readByte();
    }

    Class<? extends FloatFeatureTransformer> featureTransformerCls = (Class<? extends FloatFeatureTransformer>) SerializationUtils
            .deserialize(featureTransformerBytes);

    Constructor[] constructors = featureTransformerCls.getDeclaredConstructors();
    Constructor constructor = constructors[0];

    try {
        this.featureTransformer = (FloatFeatureTransformer) constructor.newInstance(new Object[] {});
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:dk.statsbiblioteket.util.qa.PackageScanner.java

/**
 * <b>Beware:</b> This class may throw exotic exceptions since it deals with
 * binary class data./* www .  java  2 s  .c  om*/
 *
 * @param classTarget The class to analyze.
 * @param filename    The file containing the class.
 * @return An array of ReportElements extracted from the members of the
 *         class and the class it self.
 */
@SuppressWarnings({ "unchecked" })
public final ReportElement[] analyzeClass(Class classTarget, String filename) {
    //FIXME: Filenames for internal classes does not refer to correct .java
    //file (it uses Foo$Bar.java)
    Class[] classes = classTarget.getDeclaredClasses();
    Constructor[] constructors = classTarget.getDeclaredConstructors();
    Method[] methods = classTarget.getDeclaredMethods();
    Field[] fields = classTarget.getDeclaredFields();

    List<ReportElement> elements = new ArrayList<ReportElement>();

    // Add the top level class
    ReportElement topLevel = new ReportElement(ReportElement.ElementType.CLASS, classTarget.getName(), null,
            baseSource.toString(), filename, (QAInfo) classTarget.getAnnotation(QAInfo.class));
    elements.add(topLevel);

    for (Class c : classes) {
        ReportElement classInfo = new ReportElement(ReportElement.ElementType.CLASS, c.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) c.getAnnotation(QAInfo.class));
        elements.add(classInfo);
    }

    for (Constructor c : constructors) {
        ReportElement conInfo = new ReportElement(ReportElement.ElementType.METHOD,
                c.getName().substring(c.getName().lastIndexOf(".") + 1), classTarget.getName(),
                baseSource.toString(), filename, (QAInfo) c.getAnnotation(QAInfo.class));
        elements.add(conInfo);
    }

    for (Method m : methods) {
        ReportElement metInfo = new ReportElement(ReportElement.ElementType.METHOD, m.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) m.getAnnotation(QAInfo.class));
        elements.add(metInfo);
    }

    for (Field f : fields) {
        ReportElement fInfo = new ReportElement(ReportElement.ElementType.FIELD, f.getName(),
                classTarget.getName(), baseSource.toString(), filename, (QAInfo) f.getAnnotation(QAInfo.class));
        elements.add(fInfo);
    }
    return elements.toArray(new ReportElement[elements.size()]);
}

From source file:com.netflix.simianarmy.basic.BasicSimianArmyContext.java

/**
 * Generic factory to create monkey collateral types.
 *
 * @param <T>/*from w w  w. ja  v a  2  s.c  om*/
 *            the generic type to create
 * @param implClass
 *            the actual concrete type to instantiate.
 * @return an object of the requested type
 */
private <T> T factory(Class<T> implClass) {
    try {
        // then find corresponding ctor
        for (Constructor<?> ctor : implClass.getDeclaredConstructors()) {
            Class<?>[] paramTypes = ctor.getParameterTypes();
            if (paramTypes.length != 1) {
                continue;
            }
            if (paramTypes[0].getName().endsWith("Configuration")) {
                @SuppressWarnings("unchecked")
                T impl = (T) ctor.newInstance(config);
                return impl;
            }
        }
        // Last ditch; try no-arg.
        return implClass.newInstance();
    } catch (Exception e) {
        LOGGER.error("context config error, cannot make an instance of " + implClass.getName(), e);
    }
    return null;
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedConstructors(CodeBase codeBase, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;/*from   w  w w.ja v  a  2  s. com*/
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();

        for (Constructor constructor : declaredConstructors) {
            SignatureStatus status = methodAnalyzer.apply(constructor);
            MethodSignature thisSignature = SignatureUtils.makeConstructorSignature(clazz, constructor);
            codeBase.addSignature(thisSignature, thisSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedConstructors(codeBase, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:com.sm.store.server.RemoteStore.java

private GetTrigger checkProxy(Class cls, StoreConfig storeConfig) throws Exception {
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    if (constructors.length == 1 && constructors[0].getParameterTypes().length == 2
            && cls.getName().endsWith("RebalanceProxy")) {
        Constructor<?> constructor = constructors[0];
        return (GetTrigger) constructor.newInstance(new Object[] { this, storeConfig });
    } else/*  ww w .  jav a  2  s  .  c  o m*/
        return (GetTrigger) cls.newInstance();
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

@Test
public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
        InstantiationException, IOException {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName(),
            new SubTypesScanner(false));

    Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
    for (Object clazz : allClasses) {
        String className = ((Class) clazz).getName();
        if (className.contains("com.basistech.rosette.dm")) {
            continue;
        }//from w  w  w . j ava 2  s . c o  m
        if (className.contains("Adm")) {
            continue; // these are too hard.
        }
        if (className.endsWith(".ModelTest")) {
            continue;
        }
        if (className.endsWith(".NonNullTest")) {
            continue;
        }
        if (className.endsWith("Mixin")) {
            continue;
        }

        if (className.endsWith("Builder")) {
            continue;
        }
        if (className.contains(".batch.")) {
            // there are polymorphism issues in here for this test strategy.
            continue;
        }

        Class c = Class.forName(className);
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }
        Constructor[] ctors = c.getDeclaredConstructors();
        if (ctors.length == 0) {
            continue;
        }
        Constructor ctor = ctors[0];
        if (ctor.getParameterTypes().length == 0) {
            continue; // don't want empty constructor
        }
        Object o1;
        if (Modifier.isPublic(ctor.getModifiers())) {

            boolean oldInputStreams = inputStreams;
            try {
                if (className.endsWith("ConstantsResponse")) {
                    inputStreams = false; // special case due to Object in there.
                }
                o1 = createObject(ctor);
            } finally {
                inputStreams = oldInputStreams;
            }

            // serialize
            // for a request, we might need a view
            ObjectWriter writer = mapper.writerWithView(Object.class);
            if (o1 instanceof DocumentRequest) {
                DocumentRequest r = (DocumentRequest) o1;
                if (r.getRawContent() instanceof String) {
                    writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class);
                }
            }
            String json = writer.writeValueAsString(o1);
            // deserialize
            Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz);
            // verify
            assertEquals(o1, o2);
        }
    }
}

From source file:com.github.juanmf.java2plant.render.PlantRenderer.java

private void renderClassMembers(StringBuilder sb, Class<?> aClass) {
    List<String> fields = new ArrayList<>();
    List<String> methods = new ArrayList<>();
    List<String> constructors = new ArrayList<>();

    addMembers(aClass.getDeclaredFields(), fields);
    addMembers(aClass.getDeclaredConstructors(), constructors);
    addMembers(aClass.getDeclaredMethods(), methods);

    Collections.sort(fields);/*w w  w  .  ja va 2  s.c om*/
    Collections.sort(methods);
    Collections.sort(constructors);

    for (String field : fields) {
        sb.append(field + "\n");
    }
    sb.append("--\n");
    for (String constructor : constructors) {
        sb.append(constructor + "\n");
    }
    for (String method : methods) {
        sb.append(method + "\n");
    }
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

@Inject
public void initSendMailCron() {
    if (!cronEnabled.booleanValue()) {
        return;/* w w  w.jav a  2 s. c  om*/
    }
    try {
        transport = session.getTransport("smtp");
    } catch (Exception ex) {
        logger.error("Could not initialize SMTP transport", ex);
        throw new IllegalStateException(ex);
    }
    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = new JobDetail("sendEmailJob", "sendEmailPoll", SendEmailJob.class);
        Trigger trigger = new DateIntervalTrigger("sendEmailTrigger", "sendEmailPoll",
                DateIntervalTrigger.IntervalUnit.SECOND, period.intValue());
        scheduler.setJobFactory(new JobFactory() {

            public Job newJob(TriggerFiredBundle bundle) throws SchedulerException {
                try {
                    Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
                    if (EmailServiceImpl.class.equals(jobClass.getEnclosingClass())) {
                        Constructor<? extends Job> constructor = (Constructor<? extends Job>) jobClass
                                .getDeclaredConstructors()[0];
                        constructor.setAccessible(true);
                        Job job = constructor.newInstance(EmailServiceImpl.this);
                        return job;
                    } else {
                        return jobClass.newInstance();
                    }
                } catch (Exception ex) {
                    throw new SchedulerException(ex);
                }
            }
        });
        scheduler.start();
        scheduler.scheduleJob(detail, trigger);
    } catch (Exception ex) {
        logger.error("Could not start cron job!", ex);
        throw new IllegalStateException(ex);
    }
}

From source file:org.eclipse.hudson.init.InitialSetup.java

public void invokeHudson(boolean restart) {
    final WebAppController controller = WebAppController.get();

    if (initialClassLoader == null) {
        initialClassLoader = getClass().getClassLoader();
    }/*from  w  w  w  .j  ava  2  s  .c  o m*/

    Class hudsonIsLoadingClass;
    try {
        outerClassLoader = new OuterClassLoader(initialClassLoader);

        hudsonIsLoadingClass = outerClassLoader.loadClass("hudson.util.HudsonIsLoading");
        HudsonIsLoading hudsonIsLoading = (HudsonIsLoading) hudsonIsLoadingClass.newInstance();
        Class runnableClass = outerClassLoader.loadClass("org.eclipse.hudson.init.InitialRunnable");
        Constructor ctor = runnableClass.getDeclaredConstructors()[0];
        ctor.setAccessible(true);
        InitialRunnable initialRunnable = (InitialRunnable) ctor.newInstance(controller, logger, hudsonHomeDir,
                servletContext, restart);

        controller.install(hudsonIsLoading);
        Thread initThread = new Thread(initialRunnable,
                "hudson initialization thread " + (++highInitThreadNumber));
        initThread.setContextClassLoader(outerClassLoader);
        initThread.start();

    } catch (Exception ex) {
        logger.error("Hudson failed to load!!!", ex);
    }

    /** Above replaces these lines
    controller.install(new HudsonIsLoading());
            
    new Thread("hudson initialization thread") {
    }.start();
    */
}