Example usage for com.google.common.reflect Reflection initialize

List of usage examples for com.google.common.reflect Reflection initialize

Introduction

In this page you can find the example usage for com.google.common.reflect Reflection initialize.

Prototype

public static void initialize(Class<?>... classes) 

Source Link

Document

Ensures that the given classes are initialized, as described in <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4.2"> JLS Section 12.4.2</a>.

Usage

From source file:org.glowroot.agent.it.harness.impl.JavaagentMain.java

public static void main(String[] args) throws Exception {

    // this is needed on Java 9+ now that sun.boot.class.path no longer exists, so that
    // instrumentation config auto complete can find this class in InstrumentationConfigIT
    Reflection.initialize(Container.class);

    int port = Integer.parseInt(args[0]);
    final SocketHeartbeat socketHeartbeat = new SocketHeartbeat(port);
    new Thread(socketHeartbeat).start();

    int javaagentServicePort = Integer.parseInt(args[1]);
    JavaagentServiceImpl javaagentService = new JavaagentServiceImpl();
    final EventLoopGroup bossEventLoopGroup = EventLoopGroups.create("Glowroot-IT-Harness*-GRPC-Boss-ELG");
    final EventLoopGroup workerEventLoopGroup = EventLoopGroups.create("Glowroot-IT-Harness*-GRPC-Worker-ELG");
    // need at least 2 threads, one for executeApp(), and another for handling interruptApp() at
    // the same time
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-IT-Harness*-GRPC-Executor-%d").build());
    final Server server = NettyServerBuilder.forPort(javaagentServicePort)
            .bossEventLoopGroup(bossEventLoopGroup).workerEventLoopGroup(workerEventLoopGroup)
            .executor(executor).addService(javaagentService.bindService()).build().start();
    javaagentService.setServerCloseable(new Callable</*@Nullable*/ Void>() {
        @Override/*www  . j a  v  a 2 s .  co  m*/
        public @Nullable Void call() throws Exception {
            server.shutdown();
            if (!server.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate channel");
            }
            executor.shutdown();
            if (!executor.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate executor");
            }
            if (!bossEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate gRPC boss event loop group");
            }
            if (!workerEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate gRPC worker event loop group");
            }
            socketHeartbeat.close();
            return null;
        }
    });

    // spin a bit to so that caller can capture a trace with <multiple root nodes> if desired
    for (int i = 0; i < 1000; i++) {
        timerMarkerOne();
        timerMarkerTwo();
        MILLISECONDS.sleep(1);
    }
    // non-daemon threads started above keep jvm alive after main returns
    MILLISECONDS.sleep(Long.MAX_VALUE);
}

From source file:org.glowroot.agent.weaving.BytecodeWithStackFramesMisc.java

@Override
public String executeWithReturn() {
    Reflection.initialize(Buffers.class);
    return "";
}

From source file:org.glowroot.agent.weaving.JsrMethodMisc.java

@Override
public String executeWithReturn() {
    Reflection.initialize(BundleDbPersistenceManager.class);
    return "";
}

From source file:org.glowroot.weaving.TroublesomeBytecodeMisc.java

@Override
public void execute1() {
    IsolatedWeavingClassLoader loader = (IsolatedWeavingClassLoader) getClass().getClassLoader();
    byte[] bytes = generateTroublesomeBytecode();
    Class<?> clazz = loader.weaveAndDefineClass("TroublesomeBytecode", bytes);
    Reflection.initialize(clazz);
}

From source file:org.glowroot.agent.weaving.TroublesomeBytecodeMisc.java

@Override
public void execute1() {
    IsolatedWeavingClassLoader loader = (IsolatedWeavingClassLoader) getClass().getClassLoader();
    byte[] bytes = generateTroublesomeBytecode();
    Class<?> clazz = loader.weaveAndDefineClass("TroublesomeBytecode", bytes, null);
    Reflection.initialize(clazz);
}

From source file:net.derquinse.common.meta.MetaClassMap.java

/** Returns an entry from the map or {@code null} if the entry does not exist. */
<T extends WithMetaClass> MetaClass<T> get(TypeToken<T> type) {
    MetaClass<T> metaClass = internalGet(checkNotNull(type, "The type must be provided"));
    if (metaClass == null) {
        // Try to initialize the class
        Reflection.initialize(type.getRawType());
        metaClass = internalGet(type);// w ww  .  j  a va  2s.c  o  m
    }
    return metaClass;
}

From source file:com.facebook.presto.sql.gen.CompilerUtils.java

private static Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DumpByteCodeVisitor dumpByteCode = new DumpByteCodeVisitor(new PrintStream(out));
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpByteCode.visitClass(classDefinition);
        }//from www  .  j a v  a2 s  .co m
        System.out.println(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    Map<String, byte[]> byteCodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        try {
            classDefinition.visit(cw);
        } catch (IndexOutOfBoundsException e) {
            Printer printer = new Textifier();
            StringWriter stringWriter = new StringWriter();
            TraceClassVisitor tcv = new TraceClassVisitor(null, printer, new PrintWriter(stringWriter));
            classDefinition.visit(tcv);
            throw new IllegalArgumentException("An error occurred while processing classDefinition:"
                    + System.lineSeparator() + stringWriter.toString(), e);
        }
        byte[] byteCode = cw.toByteArray();
        if (RUN_ASM_VERIFIER) {
            ClassReader reader = new ClassReader(byteCode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
        }
        byteCodes.put(classDefinition.getType().getJavaClassName(), byteCode);
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Map.Entry<String, byte[]> entry : byteCodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] byteCode : byteCodes.values()) {
            ClassReader classReader = new ClassReader(byteCode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.SKIP_FRAMES);
        }
    }
    Map<String, Class<?>> classes = classLoader.defineClasses(byteCodes);
    try {
        for (Class<?> clazz : classes.values()) {
            Reflection.initialize(clazz);
        }
    } catch (VerifyError e) {
        throw new RuntimeException(e);
    }
    return classes;
}

From source file:com.facebook.presto.bytecode.CompilerUtils.java

private static Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions,
        DynamicClassLoader classLoader) {
    ClassInfoLoader classInfoLoader = ClassInfoLoader.createClassInfoLoader(classDefinitions, classLoader);

    if (DUMP_BYTE_CODE_TREE) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DumpBytecodeVisitor dumpBytecode = new DumpBytecodeVisitor(new PrintStream(out));
        for (ClassDefinition classDefinition : classDefinitions) {
            dumpBytecode.visitClass(classDefinition);
        }/*w w w  .  j a  v a  2  s.com*/
        System.out.println(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    Map<String, byte[]> bytecodes = new LinkedHashMap<>();
    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter cw = new SmartClassWriter(classInfoLoader);
        try {
            classDefinition.visit(ADD_FAKE_LINE_NUMBER ? new AddFakeLineNumberClassVisitor(cw) : cw);
        } catch (IndexOutOfBoundsException | NegativeArraySizeException e) {
            Printer printer = new Textifier();
            StringWriter stringWriter = new StringWriter();
            TraceClassVisitor tcv = new TraceClassVisitor(null, printer, new PrintWriter(stringWriter));
            classDefinition.visit(tcv);
            throw new IllegalArgumentException("An error occurred while processing classDefinition:"
                    + System.lineSeparator() + stringWriter.toString(), e);
        }
        try {
            byte[] bytecode = cw.toByteArray();
            if (RUN_ASM_VERIFIER) {
                ClassReader reader = new ClassReader(bytecode);
                CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(System.out));
            }
            bytecodes.put(classDefinition.getType().getJavaClassName(), bytecode);
        } catch (RuntimeException e) {
            throw new CompilationException("Error compiling class " + classDefinition.getName(), e);
        }
    }

    String dumpClassPath = DUMP_CLASS_FILES_TO.get();
    if (dumpClassPath != null) {
        for (Map.Entry<String, byte[]> entry : bytecodes.entrySet()) {
            File file = new File(dumpClassPath,
                    ParameterizedType.typeFromJavaClassName(entry.getKey()).getClassName() + ".class");
            try {
                log.debug("ClassFile: " + file.getAbsolutePath());
                Files.createParentDirs(file);
                Files.write(entry.getValue(), file);
            } catch (IOException e) {
                log.error(e, "Failed to write generated class file to: %s" + file.getAbsolutePath());
            }
        }
    }
    if (DUMP_BYTE_CODE_RAW) {
        for (byte[] bytecode : bytecodes.values()) {
            ClassReader classReader = new ClassReader(bytecode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(System.err)), ClassReader.EXPAND_FRAMES);
        }
    }
    Map<String, Class<?>> classes = classLoader.defineClasses(bytecodes);
    try {
        for (Class<?> clazz : classes.values()) {
            Reflection.initialize(clazz);
        }
    } catch (VerifyError e) {
        throw new RuntimeException(e);
    }
    return classes;
}

From source file:com.facebook.presto.bytecode.ClassGenerator.java

public Map<String, Class<?>> defineClasses(List<ClassDefinition> classDefinitions) {
    ClassInfoLoader classInfoLoader = createClassInfoLoader(classDefinitions, classLoader);
    Map<String, byte[]> bytecodes = new LinkedHashMap<>();

    for (ClassDefinition classDefinition : classDefinitions) {
        ClassWriter writer = new SmartClassWriter(classInfoLoader);

        try {/*from w  ww.j  a v a2  s  .com*/
            classDefinition.visit(fakeLineNumbers ? new AddFakeLineNumberClassVisitor(writer) : writer);
        } catch (IndexOutOfBoundsException | NegativeArraySizeException e) {
            StringWriter out = new StringWriter();
            classDefinition.visit(new TraceClassVisitor(null, new Textifier(), new PrintWriter(out)));
            throw new IllegalArgumentException("Error processing class definition:\n" + out, e);
        }

        byte[] bytecode;
        try {
            bytecode = writer.toByteArray();
        } catch (RuntimeException e) {
            throw new CompilationException("Error compiling class: " + classDefinition.getName(), e);
        }

        bytecodes.put(classDefinition.getType().getJavaClassName(), bytecode);

        if (runAsmVerifier) {
            ClassReader reader = new ClassReader(bytecode);
            CheckClassAdapter.verify(reader, classLoader, true, new PrintWriter(output));
        }
    }

    dumpClassPath.ifPresent(path -> bytecodes.forEach((className, bytecode) -> {
        String name = typeFromJavaClassName(className).getClassName() + ".class";
        Path file = path.resolve(name).toAbsolutePath();
        try {
            createDirectories(file.getParent());
            Files.write(file, bytecode);
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to write generated class file: " + file, e);
        }
    }));

    if (dumpRawBytecode) {
        for (byte[] bytecode : bytecodes.values()) {
            ClassReader classReader = new ClassReader(bytecode);
            classReader.accept(new TraceClassVisitor(new PrintWriter(output)), ClassReader.EXPAND_FRAMES);
        }
    }

    Map<String, Class<?>> classes = classLoader.defineClasses(bytecodes);

    try {
        for (Class<?> clazz : classes.values()) {
            Reflection.initialize(clazz);
        }
    } catch (VerifyError e) {
        throw new RuntimeException(e);
    }

    return classes;
}