Example usage for java.lang.reflect Field set

List of usage examples for java.lang.reflect Field set

Introduction

In this page you can find the example usage for java.lang.reflect Field set.

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Bean demo = new Bean();
    Class clazz = demo.getClass();

    Field field = clazz.getField("id");
    field.set(demo, new Long(10));
    Object value = field.get(demo);
    System.out.println("Value = " + value);

    field = clazz.getField("now");
    field.set(null, new Date());
    value = field.get(null);//w  ww . java 2  s.  c  o m
    System.out.println("Value = " + value);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Set<String> set = new HashSet<String>();
    String str = "java2s.com";
    set.add(str);//from  w  ww  . j a v a  2s .c  om

    Field stringValue = String.class.getDeclaredField("value");
    stringValue.setAccessible(true);
    stringValue.set(str, str.toUpperCase().toCharArray());

    System.out.println("New value: " + str);

    String copy = new String(str); // force a copy
    System.out.println("Contains orig: " + set.contains(str));
    System.out.println("Contains copy: " + set.contains(copy));
}

From source file:E0.java

public static void main(String... args) {
    try {/*from   w  w  w  . j  a  v a  2  s. c  om*/
        ETest test = new ETest();
        Field f = test.getClass().getDeclaredField("fld");
        f.setAccessible(true);
        f.set(test, E1.A); // IllegalArgumentException

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:MyClass.java

public static void main(String[] args) {
    Class<MyClass> ppClass = MyClass.class;
    try {//from   w  w  w  . j a v  a2  s  .  c  om
        MyClass p = ppClass.newInstance();
        Field name = ppClass.getField("name");
        String nameValue = (String) name.get(p);
        System.out.println("Current name is " + nameValue);
        name.set(p, "abc");
        nameValue = (String) name.get(p);
        System.out.println("New  name is " + nameValue);
    } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
            | IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}

From source file:MyClass.java

public static void main(String[] args) {
    Class<MyClass> my = MyClass.class;
    try {/*from  w w  w .  ja va 2s.  c  o m*/
        MyClass p = my.newInstance();
        Field nameField = my.getDeclaredField("name");
        nameField.setAccessible(true);
        String nameValue = (String) nameField.get(p);
        System.out.println("Current name is " + nameValue);
        nameField.set(p, "abc");
        nameValue = (String) nameField.get(p);
        System.out.println("New name is " + nameValue);
    } catch (InstantiationException | IllegalAccessException | NoSuchFieldException | SecurityException
            | IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}

From source file:Tweedle.java

public static void main(String... args) {
    Book book = new Book();
    String fmt = "%6S:  %-12s = %s%n";

    try {//from w  ww . ja v a2s  .com
        Class<?> c = book.getClass();

        Field chap = c.getDeclaredField("chapters");
        out.format(fmt, "before", "chapters", book.chapters);
        chap.setLong(book, 12);
        out.format(fmt, "after", "chapters", chap.getLong(book));

        Field chars = c.getDeclaredField("characters");
        out.format(fmt, "before", "characters", Arrays.asList(book.characters));
        String[] newChars = { "Queen", "King" };
        chars.set(book, newChars);
        out.format(fmt, "after", "characters", Arrays.asList(book.characters));

        Field t = c.getDeclaredField("twin");
        out.format(fmt, "before", "twin", book.twin);
        t.set(book, Tweedle.DUM);
        out.format(fmt, "after", "twin", t.get(book));

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:TraceLevel.java

public static void main(String... args) {
    TraceLevel newLevel = TraceLevel.valueOf(args[0]);

    try {/* w w w  .  java2  s . c  o m*/
        MyServer svr = new MyServer();
        Class<?> c = svr.getClass();
        Field f = c.getDeclaredField("level");
        f.setAccessible(true);
        TraceLevel oldLevel = (TraceLevel) f.get(svr);
        out.format("Original trace level:  %s%n", oldLevel);

        if (oldLevel != newLevel) {
            f.set(svr, newLevel);
            out.format("    New  trace level:  %s%n", f.get(svr));
        }

        // production code should handle these exceptions more gracefully
    } catch (IllegalArgumentException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    }
}

From source file:com.heliosdecompiler.helios.Helios.java

public static void main(String[] args) {
    try {//w  w w .  j  a v  a2s .c  o m
        LanguageController languageController = new LanguageController(); // blehhhhhh
        Message.init(languageController);

        GraphicsProvider launcher = getGraphicsProvider().newInstance();

        launcher.startSplash();
        launcher.updateSplash(Message.STARTUP_PREPARING_ENVIRONMENT);

        Field defaultCharset = Charset.class.getDeclaredField("defaultCharset");
        defaultCharset.setAccessible(true);
        defaultCharset.set(null, StandardCharsets.UTF_8);
        if (!Charset.defaultCharset().equals(StandardCharsets.UTF_8))
            throw new RuntimeException("Charset: " + Charset.defaultCharset());
        if (!Constants.DATA_DIR.exists() && !Constants.DATA_DIR.mkdirs())
            throw new RuntimeException("Could not create data directory");
        if (!Constants.ADDONS_DIR.exists() && !Constants.ADDONS_DIR.mkdirs())
            throw new RuntimeException("Could not create addons directory");
        if (Constants.DATA_DIR.isFile())
            throw new RuntimeException("Data directory is file");
        if (Constants.ADDONS_DIR.isFile())
            throw new RuntimeException("Addons directory is file");

        EventBus eventBus = new AsyncEventBus(Executors.newCachedThreadPool());

        Configuration configuration = loadConfiguration();
        Class<? extends UserInterfaceController> uiController = getUIControllerImpl();

        Injector mainInjector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(MessageHandler.class).to(launcher.getMessageHandlerImpl());
                bind(UserInterfaceController.class).to(uiController);
                bind(Configuration.class).toInstance(configuration);
                bind(EventBus.class).toInstance(eventBus);
            }
        });

        mainInjector.getInstance(UserInterfaceController.class).initialize();

        launcher.updateSplash(Message.STARTUP_LOADING_GRAPHICS);
        launcher.prepare(mainInjector);

        launcher.updateSplash(Message.STARTUP_DONE);
        launcher.start();

        mainInjector.getInstance(PathController.class).reload();
        mainInjector.getInstance(UpdateController.class).doUpdate();
        handleCommandLine(args, mainInjector);
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:net.doubledoordev.backend.Main.java

public static void main(String[] args) throws Exception {
    System.setProperty("file.encoding", "UTF-8");
    Field charset = Charset.class.getDeclaredField("defaultCharset");
    charset.setAccessible(true);//from w  w  w  .j a v  a 2  s.co  m
    charset.set(null, null);

    for (String arg : args) {
        if (arg.equalsIgnoreCase("debug"))
            debug = true;
    }

    LOGGER.info("\n\n    D3Backend  Copyright (C) 2015  Dries007 & Double Door Development\n"
            + "    This program comes with ABSOLUTELY NO WARRANTY;\n"
            + "    This is free software, and you are welcome to redistribute it under certain conditions;\n"
            + "    Type `license' for details.\n\n");

    LOGGER.info("Making necessary folders...");
    mkdirs();
    LOGGER.info("Starting webserver...");

    final HttpServer webserver = new HttpServer();
    final ServerConfiguration config = webserver.getServerConfiguration();

    // Html stuff
    freemarkerHandler = new FreemarkerHandler(Main.class, TEMPLATES_PATH);
    config.addHttpHandler(freemarkerHandler);
    config.setDefaultErrorPageGenerator(freemarkerHandler);
    config.addHttpHandler(new CLStaticHttpHandler(Main.class.getClassLoader(), STATIC_PATH), STATIC_PATH);
    config.addHttpHandler(new ServerFileHandler(P2S_PATH), P2S_PATH);
    config.addHttpHandler(new ServerFileHandler(), RAW_PATH);

    // Socket stuff
    ServerMonitorSocketApplication.register();
    ServerControlSocketApplication.register();
    ServerPropertiesSocketApplication.register();
    FileManagerSocketApplication.register();
    ServerconsoleSocketApplication.register();
    ConsoleSocketApplication.register();
    AdvancedSettingsSocketApplication.register();
    UsersSocketApplication.register();

    final NetworkListener networkListener = new NetworkListener("listener",
            Strings.isBlank(SETTINGS.hostname) ? NetworkListener.DEFAULT_NETWORK_HOST : SETTINGS.hostname,
            Strings.isNotBlank(SETTINGS.certificatePath) ? SETTINGS.portHTTPS : SETTINGS.portHTTP);
    if (Strings.isNotBlank(SETTINGS.certificatePath)) {
        networkListener.setSecure(true);
        networkListener.setSSLEngineConfig(createSslConfiguration());
        webserver.addListener(new NetworkListener("redirect-listener",
                Strings.isBlank(SETTINGS.hostname) ? NetworkListener.DEFAULT_NETWORK_HOST : SETTINGS.hostname,
                SETTINGS.portHTTP));
    }
    webserver.addListener(networkListener);
    networkListener.registerAddOn(new WebSocketAddOn());
    webserver.start();

    LOGGER.info("Setting up caching...");
    Cache.init();

    if (SETTINGS.users.isEmpty()) {
        adminKey = UUID.randomUUID().toString();
        LOGGER.warn("Your userlist is empty.");
        LOGGER.warn("Make a new account and use the special admin token in the '2 + 2 = ?' field.");
        LOGGER.warn(
                "You can only use this key once. It will be regenerated if the userlist is empty when the backend starts.");
        LOGGER.warn("Admin token: " + adminKey);
    }

    LOGGER.info("Use the help command for help.");

    CommandHandler.init();
    for (Server server : SETTINGS.servers.values()) {
        server.init();
        if (server.getRestartingInfo().autoStart) {
            try {
                server.startServer();
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
        }
    }
}

From source file:GrowBufferedReader.java

public static void main(String... args) {
    try {//from w w w.j ava  2 s.co  m
        BufferedReader br = new BufferedReader(car);

        Class<?> c = br.getClass();
        Field f = c.getDeclaredField("cb");

        // cb is a private field
        f.setAccessible(true);
        char[] cbVal = char[].class.cast(f.get(br));

        char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2);
        if (args.length > 0 && args[0].equals("grow"))
            f.set(br, newVal);

        for (int i = 0; i < srcBufSize; i++)
            br.read();

        // see if the new backing array is being used
        if (newVal[srcBufSize - 1] == src[srcBufSize - 1])
            out.format("Using new backing array, size=%d%n", newVal.length);
        else
            out.format("Using original backing array, size=%d%n", cbVal.length);

        // production code should handle these exceptions more gracefully
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (IOException x) {
        x.printStackTrace();
    }
}