新增IntelliJ IDEA插件实现Bean属性复制功能

- 实现BeanCopyAction处理Alt+Insert和右键菜单触发
- 创建BeanCopyDialog对话框用于选择源和目标Bean
- 添加BeanVar数据类表示作用域内的Bean变量
- 实现自动生成b.setXxx(a.getXxx())格式的复制代码
- 支持通过getter/setter匹配进行属性复制
- 添加复制父类继承属性的选项
- 配置Gradle构建脚本和IntelliJ平台插件
- 设置.gitignore忽略IDE相关文件
- 创建README.md提供使用说明和构建指南
- 添加运行配置用于调试和测试插件
This commit is contained in:
yexuejc committed 2026-09-05 17:35:28 +08:00
commit 8bb9b4d11d
17 files changed
+896

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Build output
build/
.gradle/
.intellijPlatform/
# IDE
.idea/
*.iml
+28
View File
@@ -0,0 +1,28 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Plugin" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="IDE logs" path="$PROJECT_DIR$/.intellijPlatform/sandbox/*/*/log/idea.log" show_all="true" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--stacktrace" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>false</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<ExternalSystemDebugDisabled>false</ExternalSystemDebugDisabled>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<GradleProfilingDisabled>false</GradleProfilingDisabled>
<GradleCoverageDisabled>false</GradleCoverageDisabled>
<method v="2" />
</configuration>
</component>
+25
View File
@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="IDE logs" path="$PROJECT_DIR$/.intellijPlatform/sandbox/*/*/log-test/idea.log" show_all="true" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="check" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>true</RunAsTest>
<method v="2" />
</configuration>
</component>
+25
View File
@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Verifications" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="verifyPlugin" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+16
View File
@@ -0,0 +1,16 @@
# Changelog
本项目所有重要变更都记录在此文件中。
## [1.0.0] - 2026-09-05
### Added
- 首次发布:一键把源 JavaBean 的属性值通过 get/set 方法复制到目标 JavaBean
- 触发方式:Alt+Insert(Generate)→ Bean Copy...,或编辑器右键菜单
- 源/目标 Bean 选择对话框:
- 两个下拉框可编辑,支持下拉选择与直接输入变量名
- 光标选中变量时自动预填源/目标
- 可勾选「同时复制父类(继承)的属性」,勾选后连同父类/接口继承的 getter/setter 一起复制
- 光标选中变量触发时,生成的代码替换选区,去掉先前选中的变量名
- 构建对齐官方 IntelliJ Platform 模板(Gradle 2.x 平台插件),支持 IDE 2025.2+
+85
View File
@@ -0,0 +1,85 @@
# Bean Copy (IntelliJ IDEA 插件)
一键把源 JavaBean 的属性值,通过 get/set 方法复制到目标 JavaBean。
## 功能
在一个方法内写:
```java
A a = new A();
B b = new B();
```
按下 **Alt + Insert**(Generate)或 **右键菜单**,选择 **Bean Copy...**,
在弹出的对话框中选一个 **Source Bean(读)** 和一个 **Target Bean(写)**,
插件就会在光标处自动生成:
```java
b.setXxx(a.getXxx());
b.setYyy(a.getYyy());
// ... 每个在目标类中有同名 setter 的属性
```
- 自动识别 `getXxx()`、`isXxx()`(布尔)等 getter
- 用 `PropertyUtil` 的属性名匹配做 get/set 配对,`get / set / is` 前缀与大小写自动处理
- 只复制「源有 getter 且目标有同名 setter」的属性
- 对话框的两个下拉框**可编辑**:既能下拉选择,也能直接输入变量名
- 若光标正位于某个变量上,打开对话框时会**自动预填**源/目标为那个变量
- 光标**选中**变量触发时,生成的代码会**替换选区**,去掉先前选中的变量名
- 提供「**同时复制父类(继承)的属性**」复选框(默认不勾选),勾选后连同父类/接口继承的 getter/setter 一起复制
## 环境要求
- **JDK 21**(IntelliJ 2025.x 平台基于 JDK 21 编译)
- **IntelliJ IDEA**(开发/构建时会自动下载 2025.2 平台依赖)
## 构建技术栈
- 构建脚本位于 `build.gradle.kts` / `settings.gradle.kts` / `gradle.properties`
- 使用 **IntelliJ Platform Gradle Plugin 2.x**(`org.jetbrains.intellij.platform`)
- 目标平台 `intellijIdea("2025.2.6.2")`,支持 **2025.2+**(`since-build = 252`)
- 额外引入内置 `com.intellij.java` 插件,使 `PsiClass / PsiMethod / PsiJavaFile` 等 Java PSI 可被编译
- **Gradle 9.5** wrapper 已内置,无需自行安装 Gradle
## 构建
用 IntelliJ IDEA 打开本项目,等待 Gradle 同步完成;
或命令行(项目自带 wrapper,无需本机安装 Gradle):
```bash
./gradlew build # 产出 build/distributions/idea-plugin-copy-bean-1.0.0.zip(已让 build 依赖 buildPlugin)
./gradlew buildPlugin # 等价:仅产出插件 zip
```
> 说明:`buildPlugin` 是 IntelliJ 插件专属任务,默认不会挂到标准 `build` 生命周期上;
> 项目里已通过 `tasks.named("build") { dependsOn("buildPlugin") }` 让 `./gradlew build` 也能直接产出可安装的 zip。
## 运行调试
在 IDEA 的 Gradle 任务里(或命令行)运行:
```bash
./gradlew runIde # 启动一个带本插件的临时 IDE 实例进行调试
```
> 首次运行会自动下载平台并全量索引,耗时较长(几十分钟),属正常现象;后续会复用配置缓存/构建缓存,快很多。
## 安装到正式 IDE
1. 执行 `./gradlew build` 或 `./gradlew buildPlugin`
2. 打开 IDEA → Settings → Plugins → ⚙ → Install Plugin from Disk…
3. 选择 `build/distributions/idea-plugin-copy-bean-1.0.0.zip` 并重启 IDE
## 项目结构
```
src/main/resources/META-INF/plugin.xml # 插件描述符,注册菜单动作、声明平台版本
src/main/kotlin/top/yexuejc/beancopy/
BeanCopyAction.kt # 触发动作 + 生成逻辑(遍历源 getter → 匹配目标 setter,支持继承链)
BeanCopyDialog.kt # 源/目标 Bean 选择对话框(可编辑下拉 + 复制父类复选框)
BeanVar.kt # 作用域内 Bean 变量数据类
gradle.properties # 版本号、编译内存、Gradle 缓存开关
settings.gradle.kts # 插件仓库、Kotlin/platform 插件版本
build.gradle.kts # intellijPlatform 声明、目标平台与依赖、build→buildPlugin 绑定
```
+18
View File
@@ -0,0 +1,18 @@
plugins {
id("org.jetbrains.kotlin.jvm")
id("org.jetbrains.intellij.platform")
}
// 依赖仓库由 settings.gradle.kts 中的 dependencyResolutionManagement 统一配置
dependencies {
intellijPlatform {
// IntelliJ IDEA Community (IC),目标平台 2025.2+(build 252)
intellijIdea("2025.2.6.2")
// 把内置的 Java 插件(含 Java PSI)加入编译类路径,供本插件使用 PsiClass/PsiMethod 等
bundledPlugin("com.intellij.java")
}
}
// 挂到标准 build 生命周期:执行 ./gradlew build 也会产出可安装的插件 zip
tasks.named("build") {
dependsOn("buildPlugin")
}
+11
View File
@@ -0,0 +1,11 @@
group = top.yexuejc
version = 1.0.0
org.gradle.jvmargs=-Xmx2048m
# 是否把 Kotlin 标准库打进插件 -> https://jb.gg/intellij-platform-kotlin-stdlib
kotlin.stdlib.default.dependency = false
# 启用 Gradle 配置缓存与构建缓存
org.gradle.configuration-cache = true
org.gradle.caching = true
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+24
View File
@@ -0,0 +1,24 @@
import org.jetbrains.intellij.platform.gradle.extensions.intellijPlatform
rootProject.name = "idea-plugin-copy-bean"
pluginManagement {
plugins {
id("org.jetbrains.kotlin.jvm") version "2.1.20"
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
id("org.jetbrains.intellij.platform.settings") version "2.16.0"
}
@Suppress("UnstableApiUsage")
dependencyResolutionManagement {
repositories {
mavenCentral()
intellijPlatform {
defaultRepositories()
}
}
}
@@ -0,0 +1,189 @@
package top.yexuejc.beancopy
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.Messages
import com.intellij.psi.*
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PsiTreeUtil
/**
* 触发入口:Alt+Insert(Generate) -> Bean Copy... / 右键菜单 -> Bean Copy...
*
* 在方法作用域内选择源 Bean A 与目标 Bean B,然后遍历 A 的所有 getter,
* 在 B 中查找同名 setter,自动生成: b.setXxx(a.getXxx());
*/
class BeanCopyAction : AnAction() {
override fun update(e: AnActionEvent) {
// 注意:update 在 UI 线程频繁调用,只做轻量判断,不在 update 里解析 PSI
val editor = e.getData(CommonDataKeys.EDITOR)
val project = e.getData(CommonDataKeys.PROJECT)
val enabled = editor != null && project != null
e.presentation.isEnabled = enabled
e.presentation.isVisible = enabled
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val editor = e.getData(CommonDataKeys.EDITOR) ?: return
val file = e.getData(CommonDataKeys.PSI_FILE) as? PsiJavaFile ?: return
val offset = editor.caretModel.currentCaret.offset
val beanVars = collectBeanVariables(file, offset)
if (beanVars.size < 2) {
Messages.showInfoMessage(
project,
"在当前作用域中未找到足够的 Bean 变量,请先写如:A a = new A(); B b = new B();",
"Bean Copy"
)
return
}
// 若光标正位于某个变量上,则默认用该变量名预填源/目标
val defaultName = findSelectedVariableName(file, offset)
val dialog = BeanCopyDialog(beanVars, project, defaultName)
if (!dialog.showAndGet()) return
val source = dialog.sourceVar
val target = dialog.targetVar
if (source == null || target == null) {
Messages.showInfoMessage(
project,
"源与目标 Bean 请选择有效变量(或输入作用域内存在、且带 getter/setter 的变量名)。",
"Bean Copy"
)
return
}
val code = generateCopyCode(source, target, dialog.copyParent)
if (code == null) {
Messages.showInfoMessage(
project,
"源与目标 Bean 之间没有可复制的公共属性。",
"Bean Copy"
)
return
}
WriteCommandAction.runWriteCommandAction(project) {
val caret = editor.caretModel.currentCaret
if (caret.hasSelection()) {
// 有选区:用生成的代码替换选区,即去掉之前选中的变量名
editor.document.replaceString(caret.selectionStart, caret.selectionEnd, code)
} else {
editor.document.insertString(caret.offset, code)
}
}
}
// ---------- 生成代码 ----------
private fun generateCopyCode(source: BeanVar, target: BeanVar, copyParent: Boolean): String? {
val sourceClass = source.cls
val targetClass = target.cls
val targetName = target.variable.name ?: return null
val sourceName = source.variable.name ?: return null
// 是否把父类/接口继承的属性也纳入扫描
val sourceClasses = if (copyParent) classHierarchy(sourceClass) else listOf(sourceClass)
val targetClasses = if (copyParent) classHierarchy(targetClass) else listOf(targetClass)
val sb = StringBuilder()
var count = 0
val processed = HashSet<String>()
for (srcCls in sourceClasses) {
for (getter in srcCls.methods) {
// 只看 getter:0 个参数且符合 get/is 命名
if (!isGetter(getter)) continue
val property = PropertyUtil.getPropertyName(getter) ?: continue
// 子类已处理过的同名属性(父类覆盖场景)不再重复生成
if (!processed.add(property)) continue
// 在目标类(及其祖先)中手工查找同名 setter(避免依赖 findPropertySetter 的平台重载差异)
val setter = targetClasses.flatMap { it.methods.toList() }.firstOrNull {
isSetter(it) && PropertyUtil.getPropertyName(it) == property
} ?: continue
if (setter.parameterList.parametersCount != 1) continue
sb.append(targetName)
.append(".")
.append(setter.name)
.append("(")
.append(sourceName)
.append(".")
.append(getter.name)
.append("());\n")
count++
}
}
if (count == 0) return null
return sb.toString()
}
// 收集类 + 所有父类/接口,用于扫描继承到的属性(子类优先,自动去重)
private fun classHierarchy(cls: PsiClass): List<PsiClass> {
val result = LinkedHashSet<PsiClass>()
collectHierarchy(cls, result)
return result.toList()
}
private fun collectHierarchy(cls: PsiClass, into: LinkedHashSet<PsiClass>) {
if (!into.add(cls)) return
cls.superClass?.let { collectHierarchy(it, into) }
for (i in cls.interfaces) collectHierarchy(i, into)
}
private fun isGetter(m: PsiMethod): Boolean {
if (m.parameterList.parametersCount != 0) return false
if (m.hasModifierProperty(PsiModifier.STATIC)) return false
if (m.name == "getClass") return false
return PropertyUtil.getPropertyName(m) != null
}
private fun isSetter(m: PsiMethod): Boolean {
if (m.parameterList.parametersCount != 1) return false
if (m.hasModifierProperty(PsiModifier.STATIC)) return false
return PropertyUtil.getPropertyName(m) != null
}
// ---------- 收集作用域内的 Bean 变量 ----------
private fun collectBeanVariables(file: PsiFile, offset: Int): List<BeanVar> {
val element = file.findElementAt(offset) ?: return emptyList()
val scope = findScope(element) ?: return emptyList()
val vars = PsiTreeUtil.collectElementsOfType(scope, PsiLocalVariable::class.java)
return vars.mapNotNull { v ->
val cls = resolveBeanClass(v.type) ?: return@mapNotNull null
if (!hasGetterOrSetter(cls)) return@mapNotNull null
BeanVar(v, cls)
}
}
private fun findScope(element: PsiElement): PsiElement? {
val method = PsiTreeUtil.getParentOfType(element, PsiMethod::class.java)
if (method != null && method.body != null) return method.body
val block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock::class.java)
if (block != null) return block
val field = PsiTreeUtil.getParentOfType(element, PsiField::class.java)
if (field != null) return field
return null
}
private fun resolveBeanClass(type: PsiType): PsiClass? {
val classType = type as? PsiClassType ?: return null
return classType.resolve()
}
private fun hasGetterOrSetter(cls: PsiClass): Boolean =
cls.methods.any { isGetter(it) || isSetter(it) }
// 返回光标位置所在的局部变量名(用于预填源/目标下拉框)
private fun findSelectedVariableName(file: PsiFile, offset: Int): String? {
val element = file.findElementAt(offset) ?: return null
val refVariable = file.findReferenceAt(offset)?.resolve() as? PsiLocalVariable
val variable = refVariable ?: PsiTreeUtil.getParentOfType(element, PsiLocalVariable::class.java)
return variable?.name
}
}
@@ -0,0 +1,68 @@
package top.yexuejc.beancopy
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.util.ui.FormBuilder
import javax.swing.JCheckBox
import javax.swing.JComboBox
import javax.swing.JComponent
import javax.swing.JPanel
/**
* 选择源 Bean(读取属性)与目标 Bean(写入属性)的对话框。
*
* 两个下拉框均可编辑:既可从列表中选择,也可直接输入变量名。
* 若传入 [defaultName],打开时会把源/目标都预填为该变量。
* 可通过 [copyParent] 决定是否连父类/接口继承的属性一起复制。
*/
class BeanCopyDialog(
private val vars: List<BeanVar>,
project: Project,
defaultName: String? = null,
) : DialogWrapper(project, true) {
private val sourceBox = JComboBox(vars.toTypedArray())
private val targetBox = JComboBox(vars.toTypedArray())
private val copyParentCheck = JCheckBox("同时复制父类(继承)的属性")
val sourceVar: BeanVar? get() = resolveSelection(sourceBox)
val targetVar: BeanVar? get() = resolveSelection(targetBox)
/** 是否连父类/接口继承的属性一起复制(默认不选中) */
val copyParent: Boolean get() = copyParentCheck.isSelected
init {
title = "Bean Copy"
sourceBox.isEditable = true
targetBox.isEditable = true
prefill(defaultName)
init()
}
// 默认把源/目标都设为指定变量名对应的 BeanVar(若存在于列表中)
private fun prefill(name: String?) {
if (name.isNullOrBlank()) return
val matched = vars.firstOrNull { it.variable.name == name } ?: return
sourceBox.selectedItem = matched
targetBox.selectedItem = matched
}
// 解析下拉框当前值:选中的对象或直接输入的名称都能映射到 BeanVar
private fun resolveSelection(box: JComboBox<*>): BeanVar? {
val sel = box.selectedItem
return when (sel) {
is BeanVar -> sel
is String -> vars.firstOrNull { it.variable.name == sel }
else -> null
}
}
override fun createCenterPanel(): JComponent {
return FormBuilder.createFormBuilder()
.addLabeledComponent("Source Bean (读取属性):", sourceBox)
.addLabeledComponent("Target Bean (写入属性):", targetBox)
.addComponent(copyParentCheck)
.addComponentFillVertically(JPanel(), 0)
.panel
}
}
@@ -0,0 +1,14 @@
package top.yexuejc.beancopy
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiLocalVariable
/**
* 作用域内的一个 Bean 变量(局部变量 + 其解析出的类)。
*
* 在对话框的下拉框中以下列文本显示:
* <code>varName : ClassSimpleName</code>
*/
class BeanVar(val variable: PsiLocalVariable, val cls: PsiClass) {
override fun toString(): String = "${variable.name} : ${cls.name}"
}
+35
View File
@@ -0,0 +1,35 @@
<idea-plugin>
<id>top.yexuejc.beancopy</id>
<name>Bean Copy</name>
<vendor>yexuejc</vendor>
<description><![CDATA[
<b>Bean Copy</b> 一键把源 JavaBean 的属性值通过 get/set 方法复制到目标 JavaBean 上。
<br>
用法:在方法体内写 <code>A a = new A(); B b = new B();</code>,将光标置于方法内,<br>
按 <b>Alt+Insert</b> (Generate) 选择 <b>Bean Copy...</b>,在弹出的对话框中<br>
选择源 Bean 与目标 Bean,即可自动生成:<br>
<code>b.setXxx(a.getXxx());</code> 等所有可复制的赋值语句。
]]></description>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.java</depends>
<!-- 支持 2025.2+ 平台(build 252) -->
<idea-version since-build="252" />
<extensions defaultExtensionNs="com.intellij">
</extensions>
<actions>
<action id="top.yexuejc.beancopy.BeanCopyAction"
class="top.yexuejc.beancopy.BeanCopyAction"
text="Bean Copy..."
description="Copy property values from source bean to target bean via get/set">
<!-- Alt+Insert(Generate) 菜单 -->
<add-to-group group-id="GenerateGroup" anchor="last"/>
<!-- 编辑器右键菜单 -->
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
</actions>
</idea-plugin>