Greatly simplifies the complexities of Kotlin's reflection of Java

Overview

CatReflect

Maven Central

这是一个可以极大简化 Java 反射的复杂操作的工具,适用于 Kotlin & Java
This is a tool that greatly simplifies the complex operations of Java reflection for Kotlin & Java.

Java Usage

Quick View (Kotlin)

如果你需要大量操作反射,那么下面的方法可以帮你节省很多时间:
If you need to use reflection a lot, then the following methods can save you a lot of time

  1. 获得类 / Get Class
val static = Sample::class.new // 只可以访问静态成员 / Only static members can be accessed
val instance = Sample::class.new(1) // 创建了实例,静态和非静态成员均可访问 / Instances are created, both static and non-static members are accessible
  1. 访问函数 / Invoke Method
static.method("staticPrivate")(1, 2) // 访问双参静态函数 / call a static function with 2 parameters
instance.method("callPrivate")(1) // 访问单参成员函数 / call a member function with 1 parameter
  1. 访问属性 / Access Properties
val a = instance.prop<Int>("a") // member property
val b = static.prop<Int>("b") // static property

// 属性委托 / Property Delegation
var c by a
c = 1
log(a.get()) // a.get() = 1
// 获取及修改成员属性 / get and modify member property
a.set(2)
println(a.get()) // 2
// 获取及修改静态属性 / get and modify static property
b.set(3)
println(b.get()) // 3

Usage

Gradle: Maven Central

repositories {
    mavenCentral()
}
implementation("io.github.zsqw123:cat-reflect:$version")

Class

反射的第一步是需要获取 CatClass,它是 java.lang.Class 的包装类,可以通过 Class/KClass 来创建它,也可以使用任意一个已初始化的对象来创建 CatClass 对象并绑定实例:
The first step in reflection is to get CatClass, which is a wrapper class for java.lang.Class and can be created by Class/KClass or by using any of the initialized objects to create a CatClass object and bind the instance:

val Class<*>.new // 从 Class 获取 CatClass / create from Class<*>
val KClass<*>.new // 从 KClass 获取 CatClass / create from KClass<*>
val Any.reflect // 从已初始化对象获取 CatClass 并绑定实例 / using initialized object to create a CatClass and bind this object
// no sugar / Java:
CatClass.from(Class<*>) // `Class<*>.new` Complete call
CatClass.from("class name") // create class by class name
CatClass.fromInstance(Any) // `Any.reflect` Complete call

通过上面的方法就可以得到类,但如果要使用构造函数,那么就需要用到构造器,构造器的参数类型将被自动推断,或者手动指定
The above method will give you a class, but if you want to use constructors, then you will need to use a constructor whose parameter type will be automatically inferred, or manually specified as follows:

Class<*>.new(1, 2, 3) // Auto type
Class<*>.new[Int::class, Int::class](1, 2) // Manual type

在默认情况下,私有构造函数也是允许被调用的,如果这不符合您的预期,请使用如下方式来避免反射访问私有构造函数
By default, private constructors are also allowed to be called, but if this is not what you expect, to avoid reflection access to private constructors as follows:

CatClass.from(Class<*>, true)[Int::class, Int::class](1, 2) // Safe manual type
CatClass.from("class name", true) // safe create class by class name
CatClass.fromInstance(Any, true) // `Any.reflect` Complete call

Method

通过 catClass.method("method name") 获得 CatMethod / Get CatMethod by catClass.method("method name"):

Class<*>.new.method("awa") // static function
Class<*>.new(1, 2).method("awa") // member function
Class<*>.new.safeMethod("awa") // 使用 safeMethod 避免访问私有函数 / avoid call private function by safeMethod

调用函数可以通过 invoke() 方法调用,也可以省略它,就像普通函数调用一样,函数参数的类型将被自动推断,或者也可以使用手动指定:
Calling function can be called by the invoke() method, or it can be omitted, just like a normal function call, and the type of the function argument will be automatically inferred, or it can be manually specified using manually specified:

method("awa").invoke() // no parameter invoke
method("awa")() // no parameter invoke
method("awa")(1, 2) // Auto type
method("awa")[Int::class, Int::class](1, 2) // Manual type

Value

通过 catClass.prop("value name") 获得 CatValue / Get CatValue by catClass.prop("value name"):

注意:如果无法确定 Value 的类型,那么写成 Any 也是可以的,但此时 set 和 get 不受静态类型检查约束。
Note: If you can't determine the type of Value, it's okay to write it as Any, but then set and get are not subject to static type checking.

Class<*>.new.prop<Int>("awa") // static variable
Class<*>.new(1, 2).prop<Int>("awa") // member variable
Class<*>.new.safeProp<Int>("awa") // 使用 safeProp 避免访问变量 / avoid access private variable by safeProp

得到 CatValue 之后可以通过 get/set 方法来操作变量,或使用属性代理:

prop.set(2)
prop.get()
var c by prop // Property Delegation

LICENSE

Apache License 2.0

You might also like...
Sample Code for fake Kotlin library written in Java

Jatlin このリポジトリは ブログ記事 のためのサンプルコードです。詳細は記事をご覧ください。 プロジェクト構成 :java-lib にKotlinに偽装したJavaファイルが含まれます。 :kotlin-lib は :java-lib をビルドしたJARファイルをKotlinから読み込んで実行

Unofficial Actions on Google SDK for Kotlin and Java
Unofficial Actions on Google SDK for Kotlin and Java

Actions On Google Client Library This is a port of the official Node.js SDK to Kotlin. This can also be used from Java and any JVM language. Quick Fac

Theia - A Kotlin program used to analyze and discover backdoors in Minecraft Java 1.12.2 forge mods

Theia A Kotlin program used to analyse and discover backdoors in Minecraft Java

Write a Ghidra Extension without using Java or Eclipse!

Ghidra Extension in Kotlin using IntelliJ IDEA Write a Ghidra Extension without using Java or Eclipse! Setup Hit Use this template at the top of the r

A library for building Java only Zygisk/Riru modules.

A library for building Java only Zygisk/Riru modules.

A tool that can mock out an existing Appium session, supports both Java and Kotlin.

appium-mocker A tool that can mock out an existing Appium session, supports both Java and Kotlin. How to install latest appium-mocker Beta/Snapshots

A Java Virtual Machine written in Kotlin
A Java Virtual Machine written in Kotlin

jvm.kotlin A Java Virtual Machine written in Kotlin. Introduction jvm.kotlin is a toy JVM programmed in Kotlin. The main purpose of this project is le

⚙️ Extended gameplay mechanics and brand-new code foundations for Minecraft: Java Edition platforms

⚙️ foundation Extended gameplay mechanics and brand-new code foundations for Minecraft: Java Edition platforms. 🎏 Getting Started You can find inform

Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

EventBus EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components decouples event s

Compile time processed, annotation driven, no reflection SQLite database layer for Android

SqliteMagic Simple yet powerful SQLite database layer for Android that makes database handling feel like magic. Overview: Simple, intuitive & typesafe

DSL for JPA Criteria API without generated metamodel and reflection.
DSL for JPA Criteria API without generated metamodel and reflection.

Kotlin JDSL Kotlin JDSL is DSL for JPA Criteria API without generated metamodel and reflection. It helps you write a JPA query like writing an SQL sta

Reflex - Reflection API for Kotlin

Reflex repositories { maven { url = uri("https://repo.tabooproject.org/repos

Wrapper around the android Camera class that simplifies its usage

EasyCamera Wrapper around the android Camera class that simplifies its usage (read more about the process) Usage: // the surface where the preview wil

This Repository simplifies working with RecyclerView Adapter

AutoAdapter This Repository simplifies working with RecyclerView Adapter Gradle: Add it in your root build.gradle at the end of repositories: allproj

Wrapper around the android Camera class that simplifies its usage

EasyCamera Wrapper around the android Camera class that simplifies its usage (read more about the process) Usage: // the surface where the preview wil

A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.
A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lo

A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

A Java API for generating .java source files.

JavaPoet JavaPoet is a Java API for generating .java source files. Source file generation can be useful when doing things such as annotation processin

Owner
Pour my all love out.
null
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Codename One 1.4k Jan 9, 2023
StaticLog - super lightweight static logging for Kotlin, Java and Android

StaticLog StaticLog is a super lightweight logging library implemented in pure Kotlin (https://kotlinlang.org). It is designed to be used in Kotlin, J

Julian Pfeifer 28 Oct 3, 2022
Auto-generate the fastest possible Parcelable implementations for Java and Kotlin

This project is deprecated It will still be maintained, but no new features will be added. Please use Parcelize, as it is the official way of generati

Bradley Campbell 492 Nov 17, 2022
From Java to Kotlin Cheat Sheet

From Java to Kotlin Cheat Sheet Page: http://fabiomsr.github.io/from-java-to-kotlin/ Programmatically inspired from swift-is-like-go and visually insp

Fabio Santana 552 Dec 23, 2022
Transform java callback to kotlin suspend method.

Callback2Coroutines Transform Java callback to coroutines suspend method. 将传统Java callback 方法转换为kotlin中的suspend方法。 接入指南 根目录下加入jatpack的repository: allp

RainFool 14 May 25, 2021
Java REPL on Android with BeanShell

BeeShell Java REPL on Android with BeanShell. Useful for quickly checking some framework API behavior, or calling Java APIs with the permissions of AD

Hai Zhang 67 Dec 26, 2022
A Kotlin compiler plugin that allows Java callers to pass in null for default parameters

kotlin-null-defaults (Compiler plugin) (Gradle Plugin) ( Currently pending approval) A Kotlin compiler plugin that allows Java callers to pass in null

Youssef Shoaib 7 Oct 14, 2022
This repository is part of a Uni-Project to write a complete Compiler for a subset of Java.

Compiler This repository is part of a Uni-Project to write a complete Compiler for a subset of Java. Features error recovery using context sensitive a

null 3 Jan 10, 2022
🔨 Template for easy hosting of your Java/Kotlin libraries on GitHub

?? kotlin-jvm-library-template Another template for easy hosting your Java/Kotlin libraries on GitHub. Features boilerplate for Kotlin/Java projects w

Viktor 0 Jan 7, 2022
Kotlin and Java API for generating .swift source files.

SwiftPoet SwiftPoet is a Kotlin and Java API for generating .swift source files. Source file generation can be useful when doing things such as annota

Outfox 232 Jan 2, 2023