search
HomeJavajavaTutorialHow to create a Java extension method

    Introduction

    Use extension methods to "add" the original type without creating a new derived type, recompiling, or otherwise modifying the original type. method into an existing type. Although an extension method is a special form of static method, it can be called like an instance method of the extension type. For client code written in C# and Visual Basic, there is no significant difference between calling an extension method and calling the method actually defined in the type.

    Languages ​​that support extension methods

    In fact, many programming languages ​​support extension methods, such as C#, Visual Basic, Kotlin, etc., but our Java language has not yet supported it. JDK9 began to support the extension of java functions through jmod, and JDK16 promised to provide dynamic library calling solutions. However, as JDK8 users, if we also want to use extension methods, we have to find another way.

    C

    #
    /// 扩展方法
    public static class ExpandMethod {
        /// 两个数相加
        public static int Sum(this int num,int num2) {
            return num + num2;
        }
    }
    public class Program {
        static void Main(string[] args) {
            /// 调用位置
            Console.WriteLine(3.Sum(2));
        }
    }

    Visual Basic

    Imports System.Runtime.CompilerServices
    Module Module3
        Sub Main()
            Dim ex As New ExampleClass
            ' 调用位置
            ex.ExampleMethod("Extension method")
        End Sub 
        Class ExampleClass
            ' Define an instance method named ExampleMethod. 
            Public Sub ExampleMethod()
                Console.WriteLine("Instance method")
            End Sub 
        End Class
        <Extension()> 
        Sub ExampleMethod(ByVal ec As ExampleClass, 
                ByVal stringParameter As String)
            Console.WriteLine(stringParameter)
        End Sub 
    End Module

    Kotlin

    // 扩展函数(本类中扩展方法)
    class Test1 {
        var name: String = "boyi.chen"
    }
    fun Test1.temp() {
        println("增加扩展函数,打印扩展类的属性name=${this.name}")
    }
    fun main(args: Array<String>) {
        // 调用位置
        Test1().temp()
    }

    The protagonist appears

    Java8 itself does not support extension methods, but we can pass Implementing extension methods through plug-ins is the same as using extension methods directly. Lombok is one of the plug-ins.

    Lombok @ExtensionMethod

    Through the Lombok @ExtensionMethod annotation, it helps us generate static methods that are directly called during program compilation. Of course, the IDEA plug-in can provide better support. Let’s look at specific examples below.

    /**
     * lombok测试
     *
     * @author reboot
     */
    @ExtensionMethod(StringUtil.class)
    public class LombokTest {
        public static void main(String[] args) {
            System.out.println("".isBlank());
        }
        /**
         * 字符串工具
         *
         * @author reboot
         */
        public static class StringUtil {
            /**
             * 字符串判空
             *
             * @param targetStr 目标str
             * @return boolean
             */
            public static boolean isBlank(String targetStr) {
                return targetStr == null || "".equals(targetStr);
            }
        }
    }

    The compiled content can see that the method has been converted from "".isBlank() to LombokTest.StringUtil.isBlank(""). This is how Lombok provides us with the syntax of the extension method. Sugar, really sweet.

    How to create a Java extension method

    The above is the detailed content of How to create a Java extension method. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

    Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

    完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

    一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

    详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

    本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

    Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

    java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

    封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

    Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    Hot Tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.