Tips Proxy Java Example: Ví dụ minh họa về việc sử dụng Proxy trong Java

TricksMMO

Administrator
Staff member
## ví dụ Java proxy

Trong Java, một proxy là một đối tượng hoạt động như một sự thay thế cho một đối tượng khác.Đối tượng proxy chuyển tiếp yêu cầu đến đối tượng gốc và cũng có thể thực hiện các hành động bổ sung, chẳng hạn như ghi nhật ký hoặc lưu trữ.

Các đối tượng proxy có thể được sử dụng để:

*** Truy cập kiểm soát vào tài nguyên. ** Proxy có thể xác minh rằng người gọi có các quyền cần thiết để truy cập tài nguyên.
*** Bảo vệ một tài nguyên khỏi sửa đổi trái phép. ** Một proxy có thể thực thi các hạn chế bảo mật đối với tài nguyên, chẳng hạn như ngăn chặn nó được sửa đổi bởi người dùng trái phép.
*** Cache Kết quả của một cuộc gọi phương thức. ** Một proxy có thể lưu trữ kết quả của một cuộc gọi phương thức để các cuộc gọi tiếp theo đến phương thức không cần thực hiện cho đối tượng gốc.

Để tạo một đối tượng proxy trong Java, bạn có thể sử dụng lớp `proxy`.Lớp `proxy` có một` classloader`, `incocationHandler` và một danh sách các giao diện làm đối số.`Classloader` được sử dụng để tải các lớp của các giao diện mà đối tượng proxy thực hiện.'InvocationHandler` là một lớp thực hiện giao diện `incocationHandler`.Giao diện `incocationHandler` định nghĩa một phương thức duy nhất,` gọi () `, được gọi là khi một phương thức được gọi trên đối tượng proxy.

Ví dụ sau đây cho thấy cách tạo một đối tượng proxy lưu trữ kết quả của một cuộc gọi phương thức:

`` `java
nhập java.lang.reflect.invocationhandler;
nhập java.lang.reflect.method;
nhập java.lang.reflect.proxy;

lớp công khai Cacheproxy thực hiện InvocationHandler {

mục tiêu đối tượng riêng tư;
Bản đồ riêng <Chuỗi, Object> Cache = New Hashmap <> ();

công khai Cacheproxy (mục tiêu đối tượng) {
this.target = Target;
}

@Ghi đè
Đối tượng công khai Gọi (Proxy Object, Phương thức, Đối tượng [] args) ném có thể ném {
Chuỗi key = method.getName () + mảng.ToString (args);
if (cache.containskey (khóa)) {
trả về bộ nhớ cache.get (khóa);
}

Kết quả đối tượng = method.invoke (Target, args);
bộ nhớ cache.put (khóa, kết quả);
kết quả trả lại;
}
}
`` `

Để sử dụng `Cacheproxy`, bạn có thể tạo một đối tượng proxy cho lớp mà bạn muốn lưu trữ.Ví dụ: mã sau tạo một đối tượng proxy cho `java.util.hashmap` class:

`` `java
Hashmap <chuỗi, chuỗi> map = (hashmap <chuỗi, chuỗi>) proxy.newProxyInstance (
Hashmap.Class.GetClassLoader (),
lớp mới [] {hashmap. class},
Cacheproxy mới (Hashmap mới <chuỗi, chuỗi> ()));
`` `

Bây giờ, bạn có thể sử dụng đối tượng `map` để lưu trữ kết quả của các cuộc gọi phương thức.Ví dụ: mã sau đây lưu trữ kết quả của phương thức `get ()`:

`` `java
Chuỗi value = map.get ("khóa");
`` `

Lần tới khi bạn gọi phương thức `get ()` có cùng một khóa, giá trị sẽ được trả về từ bộ đệm thay vì được lấy từ đối tượng `hashmap` ban đầu.

## hashtags

* #Java
* #Ủy quyền
* #DesignPotype
* #caching
* #hiệu suất
=======================================
## Proxy Java Example

In Java, a proxy is an object that acts as a substitute for another object. The proxy object forwards requests to the original object and may also perform additional actions, such as logging or caching.

Proxy objects can be used to:

* **Control access to a resource.** A proxy can verify that the caller has the necessary permissions to access the resource.
* **Protect a resource from unauthorized modification.** A proxy can enforce security restrictions on the resource, such as preventing it from being modified by unauthorized users.
* **Cache the results of a method call.** A proxy can cache the results of a method call so that subsequent calls to the method do not need to be made to the original object.

To create a proxy object in Java, you can use the `Proxy` class. The `Proxy` class takes a `ClassLoader`, an `InvocationHandler`, and a list of interfaces as arguments. The `ClassLoader` is used to load the classes of the interfaces that the proxy object implements. The `InvocationHandler` is a class that implements the `InvocationHandler` interface. The `InvocationHandler` interface defines a single method, `invoke()`, which is called when a method is invoked on the proxy object.

The following example shows how to create a proxy object that caches the results of a method call:

```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CacheProxy implements InvocationHandler {

private Object target;
private Map<String, Object> cache = new HashMap<>();

public CacheProxy(Object target) {
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String key = method.getName() + Arrays.toString(args);
if (cache.containsKey(key)) {
return cache.get(key);
}

Object result = method.invoke(target, args);
cache.put(key, result);
return result;
}
}
```

To use the `CacheProxy`, you can create a proxy object for the class that you want to cache. For example, the following code creates a proxy object for the `java.util.HashMap` class:

```java
HashMap<String, String> map = (HashMap<String, String>) Proxy.newProxyInstance(
HashMap.class.getClassLoader(),
new Class[]{HashMap.class},
new CacheProxy(new HashMap<String, String>()));
```

Now, you can use the `map` object to cache the results of method calls. For example, the following code caches the results of the `get()` method:

```java
String value = map.get("key");
```

The next time you call the `get()` method with the same key, the value will be returned from the cache instead of being retrieved from the original `HashMap` object.

## Hashtags

* #Java
* #Proxy
* #designpatterns
* #caching
* #Performance
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top