apollo更新bean的属性

public class FileRefTest {


    static class Lbw{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
    @Test
    public void test() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InstantiationException {
//        Lbw lbw = new Lbw();
//        Class<? extends Lbw> aClass = lbw.getClass();
//        Field filed = aClass.getDeclaredField("name");
//
//        aClass.getFields();
//        lbw.setName("test123");


        ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(2);
        Class<?> clazz = Lbw.class;

        Field field = null;
        field = clazz.getDeclaredField("name");
        field.setAccessible(true);

        Lbw bean = (Lbw) clazz.newInstance();
        field.set(bean, "newVal");

        Field finalField = field;
        scheduleExecutor.scheduleAtFixedRate(()->{
            String mySourceFileName = "f://test.txt";
            byte[] bytes = new byte[1024];
            ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
            boolean accessible = finalField.isAccessible();
            finalField.setAccessible(true);
            finalField.setAccessible(accessible);
            
            try (FileChannel inputChannel = new FileInputStream(new File(mySourceFileName)).getChannel();
            ){

                while (inputChannel.read(byteBuffer) > 0) {
                    byteBuffer.flip();
                    String str = new String(bytes, "utf-8");
                    System.out.println(str);
                    byteBuffer.clear(); // 清空buffer
                    finalField.set(bean, str);
                    System.out.println("bean.getName()---"+bean.getName());
                }

            } catch (Exception e) {

            }
            System.out.println("======");
        }, 2, 2, TimeUnit.SECONDS);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        countDownLatch.await();
    }


}

原文地址:https://www.cnblogs.com/kltsee/p/15513628.html