All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kero.security.core.proxy.SubclassProxyWrapper Maven / Gradle / Ivy

Go to download

Kero-Security is a library for statically controlling access to properties of objects / classes.

There is a newer version: 0.1.39
Show newest version
package com.kero.security.core.proxy;

import com.kero.security.core.config.PreparedAccessConfiguration;
import com.kero.security.core.proxy.exception.CreateProxyClassException;
import com.kero.security.core.scheme.AccessProxy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.implementation.FieldAccessor;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.matcher.ElementMatchers;

public class SubclassProxyWrapper extends ProxyWrapperBase {

	public SubclassProxyWrapper(Class targetClass) {
		super(targetClass);
		
	}

	@Override
	protected Class createProxyClass() {

		boolean hasDefaultConstructor = true;
	
		try {
			
			targetClass.getDeclaredConstructor();
		}
		catch(NoSuchMethodException e) {
			
			hasDefaultConstructor = false;
		}
		
		try {
			
			return new ByteBuddy()
				.subclass(this.targetClass)
				.implement(AccessProxy.class)
				.defineField("original", Object.class, Visibility.PRIVATE)
				.defineField("pac", PreparedAccessConfiguration.class, Visibility.PRIVATE)
				.defineConstructor(Visibility.PUBLIC)
				.withParameters(Object.class, PreparedAccessConfiguration.class)
				.intercept(hasDefaultConstructor
					? MethodCall.invoke(targetClass.getDeclaredConstructor()).andThen(FieldAccessor.ofField("original").setsArgumentAt(0).andThen(FieldAccessor.ofField("pac").setsArgumentAt(1)))
					: FieldAccessor.ofField("original").setsArgumentAt(0).andThen(FieldAccessor.ofField("pac").setsArgumentAt(1)))
				.method(ElementMatchers.isPublic())
				.intercept(InvocationHandlerAdapter.toField("pac"))
				.defineMethod("getOriginal", Object.class, Visibility.PUBLIC).intercept(FieldAccessor.ofField("original"))
				.make()
				.load(ClassLoader.getSystemClassLoader())
				.getLoaded();
		}
		catch(Exception e) {
			
			throw new CreateProxyClassException(e);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy