You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by pa...@apache.org on 2022/12/21 07:26:29 UTC

[shardingsphere] branch master updated: Refactor agent ReflectionUtil (#23007)

This is an automated email from the ASF dual-hosted git repository.

panjuan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new a94208aa912 Refactor agent ReflectionUtil (#23007)
a94208aa912 is described below

commit a94208aa912525f5aeb47c528d0075c9859adc47
Author: Liang Zhang <zh...@apache.org>
AuthorDate: Wed Dec 21 15:26:21 2022 +0800

    Refactor agent ReflectionUtil (#23007)
---
 .../agent/core/util/ReflectionUtil.java            | 38 ++--------------------
 .../loader/PluginConfigurationLoaderTest.java      |  6 ++--
 .../agent/core/util/ReflectionUtilTest.java        | 33 +++++++++++++++++++
 .../agent/core/util/fixture/ReflectiveFixture.java | 28 ++++++++++++++++
 .../AbstractJDBCExecutorCallbackAdviceTest.java    | 10 +++---
 5 files changed, 72 insertions(+), 43 deletions(-)

diff --git a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/util/ReflectionUtil.java b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/util/ReflectionUtil.java
index 53c33b909e9..2820627f0b3 100644
--- a/agent/core/src/main/java/org/apache/shardingsphere/agent/core/util/ReflectionUtil.java
+++ b/agent/core/src/main/java/org/apache/shardingsphere/agent/core/util/ReflectionUtil.java
@@ -22,7 +22,6 @@ import lombok.NoArgsConstructor;
 import lombok.SneakyThrows;
 
 import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
 
 /**
  * Reflection utility.
@@ -39,47 +38,16 @@ public final class ReflectionUtil {
      */
     @SneakyThrows(ReflectiveOperationException.class)
     public static Object getFieldValue(final Object target, final String fieldName) {
-        return getField(target.getClass(), fieldName).get(target);
-    }
-    
-    private static Field getField(final Class<?> target, final String fieldName) throws NoSuchFieldException {
-        Class<?> clazz = target;
+        Class<?> clazz = target.getClass();
         while (null != clazz) {
             try {
                 Field result = clazz.getDeclaredField(fieldName);
                 result.setAccessible(true);
-                return result;
+                return result.get(target);
             } catch (final NoSuchFieldException ignored) {
             }
             clazz = clazz.getSuperclass();
         }
-        throw new NoSuchFieldException(String.format("Can not find field name `%s` in class %s.", fieldName, target));
-    }
-    
-    /**
-     * Set value to specified field.
-     * 
-     * @param target target
-     * @param fieldName field name
-     * @param value value
-     */
-    @SneakyThrows(ReflectiveOperationException.class)
-    public static void setField(final Object target, final String fieldName, final Object value) {
-        getField(target.getClass(), fieldName).set(target, value);
-    }
-    
-    /**
-     * Set value to specified static field.
-     *
-     * @param target target
-     * @param fieldName field name
-     * @param value value
-     */
-    @SneakyThrows(ReflectiveOperationException.class)
-    public static void setStaticField(final Class<?> target, final String fieldName, final Object value) {
-        Field field = getField(target, fieldName);
-        if (Modifier.isStatic(field.getModifiers())) {
-            field.set(null, value);
-        }
+        throw new NoSuchFieldException(String.format("Can not find field name `%s` in class %s.", fieldName, target.getClass()));
     }
 }
diff --git a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/config/loader/PluginConfigurationLoaderTest.java b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/config/loader/PluginConfigurationLoaderTest.java
index 89bc6d6daa0..fed9015d759 100644
--- a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/config/loader/PluginConfigurationLoaderTest.java
+++ b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/config/loader/PluginConfigurationLoaderTest.java
@@ -18,8 +18,8 @@
 package org.apache.shardingsphere.agent.core.config.loader;
 
 import org.apache.shardingsphere.agent.core.path.AgentPathBuilder;
-import org.apache.shardingsphere.agent.core.util.ReflectionUtil;
 import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
 
 import java.io.File;
 import java.io.IOException;
@@ -34,8 +34,8 @@ public final class PluginConfigurationLoaderTest {
     private static final String DEFAULT_CONFIG_PATH = "/conf/agent.yaml";
     
     @Test
-    public void assertLoad() throws IOException {
-        ReflectionUtil.setStaticField(AgentPathBuilder.class, "agentPath", new File(getResourceUrl()));
+    public void assertLoad() throws IOException, NoSuchFieldException {
+        new InstanceField(AgentPathBuilder.class.getDeclaredField("agentPath"), AgentPathBuilder.class).set(new File(getResourceUrl()));
         assertNotNull(PluginConfigurationLoader.load());
     }
     
diff --git a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/ReflectionUtilTest.java b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/ReflectionUtilTest.java
new file mode 100644
index 00000000000..98e61bb262b
--- /dev/null
+++ b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/ReflectionUtilTest.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shardingsphere.agent.core.util;
+
+import org.apache.shardingsphere.agent.core.util.fixture.ReflectiveFixture;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public final class ReflectionUtilTest {
+    
+    @Test
+    public void assertGetFieldValue() {
+        ReflectiveFixture reflectiveFixture = new ReflectiveFixture("foo");
+        assertThat(ReflectionUtil.getFieldValue(reflectiveFixture, "value"), is(reflectiveFixture.getValue()));
+    }
+}
\ No newline at end of file
diff --git a/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/fixture/ReflectiveFixture.java b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/fixture/ReflectiveFixture.java
new file mode 100644
index 00000000000..b155c1292d9
--- /dev/null
+++ b/agent/core/src/test/java/org/apache/shardingsphere/agent/core/util/fixture/ReflectiveFixture.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shardingsphere.agent.core.util.fixture;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+@RequiredArgsConstructor
+@Getter
+public final class ReflectiveFixture {
+    
+    private final String value;
+}
diff --git a/agent/plugins/tracing/test/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/advice/AbstractJDBCExecutorCallbackAdviceTest.java b/agent/plugins/tracing/test/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/advice/AbstractJDBCExecutorCallbackAdviceTest.java
index f3b50d23dc0..d4c07894bc1 100644
--- a/agent/plugins/tracing/test/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/advice/AbstractJDBCExecutorCallbackAdviceTest.java
+++ b/agent/plugins/tracing/test/src/main/java/org/apache/shardingsphere/agent/plugin/tracing/advice/AbstractJDBCExecutorCallbackAdviceTest.java
@@ -20,7 +20,6 @@ package org.apache.shardingsphere.agent.plugin.tracing.advice;
 import lombok.Getter;
 import lombok.SneakyThrows;
 import org.apache.shardingsphere.agent.advice.TargetAdviceObject;
-import org.apache.shardingsphere.agent.core.util.ReflectionUtil;
 import org.apache.shardingsphere.agent.plugin.tracing.AgentRunner;
 import org.apache.shardingsphere.agent.plugin.tracing.MockDataSourceMetaData;
 import org.apache.shardingsphere.infra.database.metadata.DataSourceMetaData;
@@ -32,6 +31,7 @@ import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.J
 import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;
 import org.junit.runner.RunWith;
 import org.mockito.internal.util.reflection.FieldReader;
+import org.mockito.internal.util.reflection.InstanceField;
 
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
@@ -71,7 +71,7 @@ public abstract class AbstractJDBCExecutorCallbackAdviceTest implements AdviceTe
         when(connection.getMetaData()).thenReturn(databaseMetaData);
         when(statement.getConnection()).thenReturn(connection);
         executionUnit = new JDBCExecutionUnit(new ExecutionUnit("mock.db", new SQLUnit("select 1", Collections.emptyList())), null, statement);
-        JDBCExecutorCallback mock = mock(JDBCExecutorCallback.class, invocation -> {
+        JDBCExecutorCallback mockedJDBCExecutorCallback = mock(JDBCExecutorCallback.class, invocation -> {
             switch (invocation.getMethod().getName()) {
                 case "getAttachment":
                     return attachment;
@@ -83,11 +83,11 @@ public abstract class AbstractJDBCExecutorCallbackAdviceTest implements AdviceTe
             }
         });
         Map<String, DataSourceMetaData> cachedDatasourceMetaData =
-                (Map<String, DataSourceMetaData>) new FieldReader(mock, JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA")).read();
+                (Map<String, DataSourceMetaData>) new FieldReader(mockedJDBCExecutorCallback, JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA")).read();
         cachedDatasourceMetaData.put("mock_url", new MockDataSourceMetaData());
         Map<String, DatabaseType> storageTypes = new LinkedHashMap<>(1, 1);
         storageTypes.put("mock.db", new MySQLDatabaseType());
-        ReflectionUtil.setField(mock, "storageTypes", storageTypes);
-        targetObject = (TargetAdviceObject) mock;
+        new InstanceField(JDBCExecutorCallback.class.getDeclaredField("storageTypes"), mockedJDBCExecutorCallback).set(storageTypes);
+        targetObject = (TargetAdviceObject) mockedJDBCExecutorCallback;
     }
 }