Home Java javaTutorial Analysis of JDK dynamic proxy examples in java

Analysis of JDK dynamic proxy examples in java

Apr 30, 2023 pm 01:16 PM
java jdk

1. Description

Java provides a dynamic proxy class Proxy. Proxy is not a class of what we call proxy objects, but provides a static method for creating proxy objects. Method (newProxyInstance) to obtain the proxy object.

2. Example

public class HelloWorld {
    public static void main(String[] args) {
        // 获取代理对象
        ProxyFactory factory = new ProxyFactory();
        
        SellTickets proxyObject = factory.getProxyObject();
        
        proxyObject.sell();
    }
}
 
// 卖票接口
interface SellTickets {
    void sell();
}
 
// 火车站,火车站具有卖票功能,所以需要实现SellTickets接口
class TrainStation implements SellTickets {
    @Override
    public void sell() {
        System.out.println("火车站卖票");
    }
}
 
// 代理工厂,用来创建代理对象
class ProxyFactory {
    private TrainStation station = new TrainStation();
 
    public SellTickets getProxyObject() {
        // 使用Proxy获取代理对象
 
        /**
         * newProxyInstance() 方法参数说明:
         *  ClassLoader loader: 类加载器,用于加载代理类,使用真实对象的类加载器即可
         *  Class<?>[] interfaces:真实对象所实现的接口,代理模式真实对象和代理对象实现相同的接口
         *  InvocationHandler h:代理对象的调用处理程序
         */
 
        SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(
                station.getClass().getClassLoader(),
                new InvocationHandler() {
                    /**
                     * InvocationHandle中invoke方法参数说明:
                     *  proxy:代理对象
                     *  method:对应于在代理对象上调用的方法的Method实例
                     *  args:代理对象调用接口方法是传递的实际参数
                     */
                    
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理点收取一些服务费用(JDK动态代理方法)");
                        
                        // 执行真实对象
                        Object result = method.invoke(station, args);
                        return result;
                    }
                });
        return sellTickets;
    }
}

The above is the detailed content of Analysis of JDK dynamic proxy examples in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CVE-2024-20674|Windows Kerberos security function bypasses vulnerability CVE-2024-20674|Windows Kerberos security function bypasses vulnerability Sep 02, 2025 pm 05:18 PM

0x00 Foreword Kerberos was created by MIT as a solution to these cybersecurity issues. Is a client/server architecture that provides security verification processing over the network. Through verification, the identity of the sender and receiver of network transactions can be ensured to be true. The service can also verify the validity (integrity) of data passed back and forth and encrypt the data during transmission (confidentiality). 0x01 Vulnerability Description An attacker with access to a victim network can exploit this vulnerability by establishing an intermediate (MITM) attack or other local network spoofing techniques, and then sending a malicious Kerberos message to the client victim's computer and pretending to be a Kerberos authentication server. 0x02CVE

Wi-Fi calling not working Wi-Fi calling not working Sep 05, 2025 am 04:44 AM

EnsureyourdeviceandcarriersupportWi-Ficallingandenableitinsettings—iPhone:Settings>Phone>Wi-FiCalling;Android:Settings>Network&Internet>Mobilenetwork>Advanced>Wi-FiCalling;confirmcarriercompatibilityandcompleteemergencyaddressre

What is the Stream API in Java? What is the Stream API in Java? Sep 01, 2025 am 08:51 AM

TheStreamAPIinJavaisafunctionaltoolforprocessingsequencesofelementsfromsourceslikecollectionsorarrayswithoutstoringormodifyingtheoriginaldata,supportingoperationssuchasfilter,map,andreduceinadeclarativeway,withintermediateoperationslikefilterandmapbe

How to Structure a Scalable Java Monolith How to Structure a Scalable Java Monolith Sep 01, 2025 am 08:42 AM

Usefeature-basedpackagingandtoolslikeArchUnittoenforcemoduleboundaries.2.Decouplemoduleswithdomaineventsandsharedcontractsinsteadofdirectcalls.3.Optimizeperformanceviastatelessservices,caching,databasetuning,andasyncprocessing.4.Structurebuildswithmo

What are functional interfaces in Java? What are functional interfaces in Java? Sep 02, 2025 am 02:07 AM

FunctionalinterfacesinJavaareinterfaceswithexactlyoneabstractmethod,servingasthefoundationforlambdaexpressionsandmethodreferences,enablingfunctionalprogrammingfeatures;theycanincludedefault,static,andObjectclassmethodswithoutbreakingthesingle-abstrac

Notepad   how to change case (uppercase/lowercase) Notepad how to change case (uppercase/lowercase) Sep 03, 2025 am 09:22 AM

TochangetextcaseinNotepad ,firstselectthetext,thengotoEdit>ConvertCaseToandchoosethedesiredoption:1.UPPERCASE–convertsalltexttouppercase.2.lowercase–convertsalltexttolowercase.3.TitleCase–capitalizesthefirstletterofeachword.4.Sentencecase–capital

How to get the file extension from a String in Java? How to get the file extension from a String in Java? Sep 16, 2025 am 03:40 AM

TogetafileextensioninJava,uselastIndexOf()tofindthelastdotandextractthesubstringafterit,ensuringthedotisn'tatindex0orabsent;forcleanercode,useApacheCommonsIO’sFilenameUtils.getExtension(),whichhandlesedgecaseslikehiddenfilesandpathswithmultipledots.

How do you search for an element in an array in Java? How do you search for an element in an array in Java? Sep 02, 2025 am 02:03 AM

The best way to search for array elements in Java depends on whether the array is sorted and its performance requirements: for small unsorted arrays, use linear search (time complexity O(n)); for sorted arrays, use Arrays.binarySearch() (time complexity O(logn)); if you use object arrays and pursue simplicity, you can convert to List and call contains() or indexOf(); when you prefer functional style in Java 8, you can use Arrays.stream().anyMatch() to implement a simple line of code, but the performance is slightly lower than that of traditional loops, so choosing methods requires weighing performance, readability and whether the data is sorted.

See all articles