ByteBuddy subclass constructor - java

I am trying to create a subclass of an abstract class in bytebuddy and want to override the constructor with my own function. I can not make it work with defineConstructor.
Superclass:
public abstract class AbstractDMTable {
protected HashMap<String, DMEntry<?>> parameterMap;
public DMEntry<?> getParameter(String paramName) {
if (parameterMap.containsKey(paramName))
return parameterMap.get(paramName);
return null;
}...
Subclass:
public class DMTable_DEBUGOUT extends AbstractDMTable {
/**
* Table entry
* prints the value of the specified parameter
*/
public DMEntry<DMEntry<?>> DEBUG_PARAM;
/**
* Table entry
* execution interval of the step handler (s)
*/
public DMEntry<Double> EXEC_INTERVAL;
/**
* Table entry
* active / not active status of this subsystem
*/
public DMEntry<Boolean> IS_ACTIVE;
/**
* Standard constructor. Creates a new table and initializes all entry fields with all entry values set to {#code null}
*/
public DMTable_DEBUGOUT() {
super();
DEBUG_PARAM = new DMEntry<>();
parameterMap.put("DEBUG_PARAM", DEBUG_PARAM);
EXEC_INTERVAL = new DMEntry<>();
parameterMap.put("EXEC_INTERVAL", EXEC_INTERVAL);
IS_ACTIVE = new DMEntry<>();
parameterMap.put("IS_ACTIVE", IS_ACTIVE);
}
}
My ByteBuddy:
DynamicType.Builder<? extends AbstractDMTable> subsystem = new ByteBuddy().subclass(AbstractDMTable.class)
.name("DMTable_" + name).defineConstructor(Collections.<Class<AbstractDMTable>> emptyList(), Visibility.PUBLIC);
for (Entry<String, Pair<String, String>> p : t.getValue().entrySet()) {
subsystem.defineField(p.getKey(), this.createSubSystemEntry(p).getClass(), Visibility.PUBLIC);
}
// subsystem.defineConstructor(Arrays.<Class<AbstractDMTable>>
// asList(int.class), Visibility.PUBLIC);
return subsystem.make().load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
The Error:
defineConstructor(ModifierContributor.ForMethod...) in the type
DynamicType.Builder<AbstractDMTable> is not applicable for the
arguments (List<Class<?>>, Visibility) DynamicDatabaseGenerator.java
line 66 Java Problem

You are using the default constructor strategy which imitates the super class constructors. The subclass method is overloaded to avoid this duplicate definition by using a different constructor strategy that does not imitate the super class.
Also, you should update Byte Buddy, this way you would get a better error message.

Related

Enums implementing interface are rejected by verifier (java.lang.VerifyError)

I'm using enums for units of different physical quantities, like meter and miles for the DISTANCE. To use them in a generic way there is an interface Unit which has the method convert(double).
To load the preferred units, a singleton is used:
public class UnitPreferences {
private static UnitPreferences sInstance;
private HashMap<PhysicalQuantity, Unit> mUnits;
/**
* Returns the instance of the preferred units collection.
*
* #param context the context
* #return Instance of the preferred units collection.
*/
public static UnitPreferences from(Context context) {
if (sInstance == null) {
sInstance = new UnitPreferences(context);
}
return sInstance;
}
/**
* Creates a new set of preferred units by fetching them from the Shared Preferences.
*
* #param context the resources
*/
private UnitPreferences(Context context) {
// Load the preferred units from SharedPreferences and put them in the mUnits HashMap
}
/**
* Returns all units of a specific physical quantity.
*
* #param physicalQuantity the physical quantity
* #return All units available to this physical quantity.
*/
private Unit[] getAllUnits(PhysicalQuantity physicalQuantity) {
switch (physicalQuantity) {
case DISTANCE:
return DistanceUnit.values();
// others...
default:
throw new RuntimeException("No units defined for " + physicalQuantity);
}
}
/**
* Returns the preferred unit of a physical quantity.
*
* #param phQuantity the physical quantity
* #return The preferred unit.
*/
public Unit getPreferredUnit(PhysicalQuantity phQuantity) {
return mUnits.get(phQuantity);
}
}
The PhysicalQuantity enum:
public enum PhysicalQuantity {
DISTANCE,
// others...
}
The Unit interface:
public interface Unit {
double convert(double value);
}
The DistanceUnit implementing the Unit interface:
public enum DistanceUnit implements Unit {
KILOMETER(R.string.unit_km, "km"),
MILES(R.string.unit_mi, "mi");
public static final double KM_PER_MI = 1.609344d;
private int label;
private String id;
DistanceUnit(int label, String id) {
this.label = label;
this.id = id;
}
#Override
public double convert(double meters) {
double km = meters / 1000d;
if (this == MILES) return km / KM_PER_MI;
return km;
}
}
The Problem:
The exception is thrown the first time I'm using the units:
Unit distanceUnit = UnitPreferences.from(context).getPreferredUnit(DISTANCE);
When I implemented it everything worked fine, now after it was merged into the master I'm getting a VerifyError
java.lang.VerifyError: Verifier rejected class com.example.app.UnitPreferences: com.example.app.Unit[]
com.example.app.UnitPreferences.getAllUnits(com.example.app.PhysicalQuantity) failed to verify:
com.example.app.units.Unit[] com.example.app.UnitPreferences.getAllUnits(com.example.app.PhysicalQuantity):
[0x28] returning 'Reference: java.lang.Enum[]', but expected from declaration 'Reference: com.example.app.Unit[]'
(declaration of 'com.example.app.UnitPreferences' in /data/app/com.example.app-2/base.apk:classes32.dex)
I've already cleaned and rebuild several times and turned off Instant Run. Can anyone give me a hint how to fix this error?
Just looked into the stacktrace a little more and it says:
returning 'Reference: Enum[]', but expected from declaration 'Reference: Unit[]'
in getAllUnits()
Casting the returned enums of getAllUnits() to Unit[] manually fixed the issue although there is a hint:
Casting 'DistanceUnit.values()' to 'Unit[]' is redundant
This part seems key:
returning 'Reference: java.lang.Enum[]', but expected from declaration 'Reference: com.example.app.Unit[]
So you are returning an enum array when you should be returning a unit array. Change either the return type of the method, or simply pack the DistanceUnit values into a list to fix the problem.
I would recommend using List<Unit> as your return type instead of Unit[]. See this for reference. To do so, call Arrays.asList(DistanceUnit.values()) when instantiating your list.

Can't be resolved to a type

I have a service interface that reads thus
package services;
import domain.Items;
public interface IItemsService extends IService {
public final String NAME = "IItemsService";
/** Places items into the database */
public void storeItem(Items items);
/** Retrieves items from the database
*
* #param category
* #param amount
* #param color
* #param type
* #return
* #throws ClassNotFoundException
*/
public Items getItems (String category, float amount, String color, String type) throws ItemNotFoundException, ClassNotFoundException;
}
And a factory that looks like this...
package services;
public class Factory {
public Factory(){}
#SuppressWarnings("unchecked")
public IService getService(String name) throws ServiceLoadException {
try {
Class c = Class.forName(getImplName(serviceName));
return (IService)c.newInstance();
} catch (Exception e) {
throw new ServiceLoadException(serviceName + "not loaded");
}
}
private String getImplName (String name) throws Exception {
java.util.Properties props = new java.util.Properties();
java.io.FileInputStream fis = new java.io.FileInputStream("properties.txt");
props.load(fis);
fis.close();
return props.getProperty(serviceName);
}
}
This should be really simple - but I keep getting two errors - IService cannot be resolved to a type (on both the factory and the service) and also an serviceName cannot be resolved into a variable error in the factory. I know I am missing something simple...
Regarding the type error: if IService is not in the package services, then IItemService will not have access to it and you will need to import some.package.name.IService.
The second answer is simple: in the getService and getImplName methods, the parameter is named name. In the method bodies, you're referring to it as serviceName. You should probably change name to serviceName in each of them.
If, on the other hand, you're trying to access an instance variable, note that in Java you have to declare all instance variables before you can access (read from/write to) them. You would need to modify the class as such:
public class Factory {
private String serviceName;
public Factory () {}
// other code
}
Well the second error is simple: there isn't a variable called serviceName. If you think there is, point to its declaration. I suspect you meant to use the parameter - in which case just change the parameter name to match the name you're trying to use:
public IService getService(String serviceName) throws ServiceLoadException
...
private String getImplName (String serviceName) throws Exception
This was a pretty simple error - you should think about what bit of your diagnosis let you down in working it out for yourself. (You should also indent your code more sensibly, btw.)
As for IService being missing - we have no idea where IService is meant to be declared, which makes it very hard to help you on this front...

When is JMXBean initialised

IMEI I am new to MXbeans. I want to understand when is the MXBean actually initialized, in the application which I am supporting we have a notification system and I can not see my MXBean in JConsole until there is some notification arriving. Here is a code of my MXBean.
package mecomaany.instrumentation;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import BulkCMIRP_MxBean;
import SoapIRPLogger;
/**
* This dynamic MBean exposes a method to return the 10 latest Basic CM
* operations.
*
* #author eshtrom
*
*/
public class BasicCMIRP_MxBean implements DynamicMBean{
private static final String CLASS_NAME = BasicCMIRP_MxBean.class.getCanonicalName();
private static final String MX_BEAN_NAME = BasicCMIRP_MxBean.class.getCanonicalName() + ":Type=BasicCMIRP_MxBean";
private static final String BEAN_DESCRIPTION = "Instrumentation bean for SOAP Basic CM IRP.";
private static final int NUM_OPERATIONS_TO_RECORD = 10;
private final ArrayList<String> basicCMOperations = new ArrayList<String>();
/**
* Register the bean. This is a best effort attempt. If registration fails
* we'll report it but nothing more.
*/
public BasicCMIRP_MxBean() {
registerMxBean();
}
/**
* Attempt to unregister and clean up the MX beans.
*/
public void destroy() {
basicCMOperations.clear();
unregisterMxBean();
}
/**
* This method returns a description of this bean to the JMX interface. The
* description is just a list of names of the currently stored attributes.
*/
public synchronized MBeanInfo getMBeanInfo() {
final MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
final MBeanOperationInfo[] operations = { new MBeanOperationInfo("getBasicCMInstrumentation", "Get instrumentation Basic CM IRP bean.", null, "String[]",
MBeanOperationInfo.INFO) };
return new MBeanInfo(this.getClass().getName(), BEAN_DESCRIPTION, attributes, null, operations, null);
}
/**
* Callback to execute methods exposed by this dynamic MBean.
*/
public Object invoke(final String actionName, final Object[] params, final String[] signature) throws MBeanException, ReflectionException {
SoapIRPLogger.enter(CLASS_NAME, "invoke");
if (actionName != null) {
if (actionName.equals("getBulkCMInstrumentation")) {
return getBasicCMInstrumentation();
}
}
SoapIRPLogger.exit(CLASS_NAME, "invoke");
throw new ReflectionException(new NoSuchMethodException(actionName));
}
/**
* Construct a human readable very of the last 10 operations and return it.
*
* #return string array as an object.
*/
private Object getBasicCMInstrumentation() {
SoapIRPLogger.enter(CLASS_NAME, "getBasicCMInstrumentation");
String[] result = new String[basicCMOperations.size()];
int index = 0;
for (String operation : basicCMOperations) {
result[index] = operation;
index++;
}
SoapIRPLogger.exit(CLASS_NAME, "getBasicCMInstrumentation");
return result;
}
/**
* No attributes are writable so this method will throw an exception.
*/
public void setAttribute(final Attribute arg0) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
throw new AttributeNotFoundException("All attributes on this bean are read only.");
}
/**
* No attributes are writable so this method will return an empty list.
*/
public AttributeList setAttributes(final AttributeList arg0) {
return new AttributeList();
}
public Object getAttribute(final String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
throw new AttributeNotFoundException("No attributes are defined on this MX bean.");
}
/**
* No attributes are readable so this method will return an empty list.
*/
public AttributeList getAttributes(final String[] attributes) {
return new AttributeList();
}
/**
* Add or update and instrumentation attribute. A null attribute name will
* be ignored.
*
* #param name
* #param value
*/
public void updateInstrumentationAttibute(final String name, final String value) {
// The only attribute that this bean supports is Bulk CM operations.
if (name.compareTo("BasicCM_Operations") == 0) {
basicCMOperations.add(value);
// We'll only record a maximum of 10 operations. If we exceed the
// max, remove the oldest.
if (basicCMOperations.size() > NUM_OPERATIONS_TO_RECORD) {
basicCMOperations.remove(0);
}
}
}
public ObjectName getBeanName() throws MalformedObjectNameException, NullPointerException {
// Construct the ObjectName for the MBean we will register
return new ObjectName(MX_BEAN_NAME);
}
/**
* Register the bean.
*/
protected void registerMxBean() {
try {
ManagementFactory.getPlatformMBeanServer().registerMBean(this, this.getBeanName());
} catch (Exception e) {
SoapIRPLogger.exception(CLASS_NAME, "Constructor", "Failed to register BulkCMIRP_MxBean management beans.", e);
}
}
protected void unregisterMxBean() {
try {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(this.getBeanName());
} catch (Exception e) {
// Suppress exceptions, we're closing down anyway.
}
}
}
Loner;
Your MXBean should be visible in JConsole as soon as you construct it, since the constructor calls registerMxBean() which registers the MBean with the platform MBeanServer.
Assuming your JConsole is already running when the MBean is registered, JConsole's view of the MBean will be dictated by the first instance of the MBeanInfo that is generated on registration. Since you coded this as a DynamicMBean, I wonder if your intent was to periodically modify the MBeanInfo, but be aware that once a JConsole connection has retrieved the MBeanInfo for a registered bean, it will not refresh it. If the MBeanInfo changes, you must closed the connection in JConsole and open it again.
Consequently, your issue may be outside the code you have supplied, or more simply put, when is the instance of BasicCMIRP_MxBean created ?
Your comment about not seeing the bean until notifications start arriving makes me wonder if you mean that:
A. You cannot see the MBean until notifications start arriving, in which case I would assume that there is some activation code that creates the instance when a [the first ?] notification arrives, or
B. What you mean is that you cannot see specific properties of the MBean until notifications start arriving.
Perhaps you could clarify the larger picture here.
Some additional observations that may be unrelated:
The MBeanInfo you are generating specifies that the one and only operation is called getBasicCMInstrumentation (basic), but your invoke handler only attempts to decode an operation called getBulkCMInstrumentation (bulk). JConsole is supplied the MBeanInfo in order to render the operations so the console believes that the operation is called basic but the MBean will only respond to a request called bulk.
The signature for method getBasicCMInstrumentation returns an Object but what the code really returns is a String[]. This may work because your MBeanInfo specifies that a String[] is returned, but for consistency and clarity I would change the method signature.
//Nicholas

Does PHP have an answer to Java style class generics?

Upon building an MVC framework in PHP I ran into a problem which could be solved easily using Java style generics. An abstract Controller class might look something like this:
abstract class Controller {
abstract public function addModel(Model $model);
There may be a case where a subclass of class Controller should only accept a subclass of Model. For example ExtendedController should only accept ReOrderableModel into the addModel method because it provides a reOrder() method that ExtendedController needs to have access to:
class ExtendedController extends Controller {
public function addModel(ReOrderableModel $model) {
In PHP the inherited method signature has to be exactly the same so the type hint cannot be changed to a different class, even if the class inherits the class type hinted in the superclass. In java I would simply do this:
abstract class Controller<T> {
abstract public addModel(T model);
class ExtendedController extends Controller<ReOrderableModel> {
public addModel(ReOrderableModel model) {
But there is no generics support in PHP. Is there any solution which would still adhere to OOP principles?
Edit
I am aware that PHP does not require type hinting at all but it is perhaps bad OOP. Firstly it is not obvious from the interface (the method signature) what kind of objects should be accepted. So if another developer wanted to use the method it should be obvious that objects of type X are required without them having to look through the implementation (method body) which is bad encapsulation and breaks the information hiding principle. Secondly because there's no type safety the method can accept any invalid variable which means manual type checking and exception throwing is needed all over the place!
It appears to work for me (though it does throw a Strict warning) with the following test case:
class PassMeIn
{
}
class PassMeInSubClass extends PassMeIn
{
}
class ClassProcessor
{
public function processClass (PassMeIn $class)
{
var_dump (get_class ($class));
}
}
class ClassProcessorSubClass extends ClassProcessor
{
public function processClass (PassMeInSubClass $class)
{
parent::processClass ($class);
}
}
$a = new PassMeIn;
$b = new PassMeInSubClass;
$c = new ClassProcessor;
$d = new ClassProcessorSubClass;
$c -> processClass ($a);
$c -> processClass ($b);
$d -> processClass ($b);
If the strict warning is something you really don't want, you can work around it like this.
class ClassProcessor
{
public function processClass (PassMeIn $class)
{
var_dump (get_class ($class));
}
}
class ClassProcessorSubClass extends ClassProcessor
{
public function processClass (PassMeIn $class)
{
if ($class instanceof PassMeInSubClass)
{
parent::processClass ($class);
}
else
{
throw new InvalidArgumentException;
}
}
}
$a = new PassMeIn;
$b = new PassMeInSubClass;
$c = new ClassProcessor;
$d = new ClassProcessorSubClass;
$c -> processClass ($a);
$c -> processClass ($b);
$d -> processClass ($b);
$d -> processClass ($a);
One thing you should bear in mind though, this is strictly not best practice in OOP terms. If a superclass can accept objects of a particular class as a method argument then all its subclasses should also be able of accepting objects of that class as well. Preventing subclasses from processing classes that the superclass can accept means you can't use the subclass in place of the superclass and be 100% confident that it will work in all cases. The relevant practice is known as the Liskov Substitution Principle and it states that, amongst other things, the type of method arguments can only get weaker in subclasses and the type of return values can only get stronger (input can only get more general, output can only get more specific).
It's a very frustrating issue, and I've brushed up against it plenty of times myself, so if ignoring it in a particular case is the best thing to do then I'd suggest that you ignore it. But don't make a habit of it or your code will start to develop all kinds of subtle interdependencies that will be a nightmare to debug (unit testing won't catch them because the individual units will behave as expected, it's the interaction between them where the issue lies). If you do ignore it, then comment the code to let others know about it and that it's a deliberate design choice.
Whatever the Java world invented need not be always right. I think I detected a violation of the Liskov substitution principle here, and PHP is right in complaining about it in E_STRICT mode:
Cite Wikipedia: "If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program."
T is your Controller. S is your ExtendedController. You should be able to use the ExtendedController in every place where the Controller works without breaking anything. Changing the typehint on the addModel() method breaks things, because in every place that passed an object of type Model, the typehint will now prevent passing the same object if it isn't accidentally a ReOrderableModel.
How to escape this?
Your ExtendedController can leave the typehint as is and check afterwards whether he got an instance of ReOrderableModel or not. This circumvents the PHP complaints, but it still breaks things in terms of the Liskov substitution.
A better way is to create a new method addReOrderableModel() designed to inject ReOrderableModel objects into the ExtendedController. This method can have the typehint you need, and can internally just call addModel() to put the model in place where it is expected.
If you require an ExtendedController to be used instead of a Controller as parameter, you know that your method for adding ReOrderableModel is present and can be used. You explicitly declare that the Controller will not fit in this case. Every method that expects a Controller to be passed will not expect addReOrderableModel() to exist and never attempt to call it. Every method that expects ExtendedController has the right to call this method, because it must be there.
class ExtendedController extends Controller
{
public function addReOrderableModel(ReOrderableModel $model)
{
return $this->addModel($model);
}
}
My workaround is the following:
/**
* Generic list logic and an abstract type validator method.
*/
abstract class AbstractList {
protected $elements;
public function __construct() {
$this->elements = array();
}
public function add($element) {
$this->validateType($element);
$this->elements[] = $element;
}
public function get($index) {
if ($index >= sizeof($this->elements)) {
throw new OutOfBoundsException();
}
return $this->elements[$index];
}
public function size() {
return sizeof($this->elements);
}
public function remove($element) {
validateType($element);
for ($i = 0; $i < sizeof($this->elements); $i++) {
if ($this->elements[$i] == $element) {
unset($this->elements[$i]);
}
}
}
protected abstract function validateType($element);
}
/**
* Extends the abstract list with the type-specific validation
*/
class MyTypeList extends AbstractList {
protected function validateType($element) {
if (!($element instanceof MyType)) {
throw new InvalidArgumentException("Parameter must be MyType instance");
}
}
}
/**
* Just an example class as a subject to validation.
*/
class MyType {
// blahblahblah
}
function proofOfConcept(AbstractList $lst) {
$lst->add(new MyType());
$lst->add("wrong type"); // Should throw IAE
}
proofOfConcept(new MyTypeList());
Though this still differs from Java generics, it pretty much minimalizes the extra code needed for mimicking the behaviour.
Also, it is a bit more code than some examples given by others, but - at least to me - it seems to be more clean (and more simliar to the Java counterpart) than most of them.
I hope some of you will find it useful.
Any improvements over this design are welcome!
I did went through the same type of problem before. And I used something like this to tackle it.
Class Myclass {
$objectParent = "MyMainParent"; //Define the interface or abstract class or the main parent class here
public function method($classObject) {
if(!$classObject instanceof $this -> objectParent) { //check
throw new Exception("Invalid Class Identified");
}
// Carry on with the function
}
}
You can consider to switch to Hack and HHVM. It is developed by Facebook and full compatible to PHP. You can decide to use <?php or <?hh
It support that what you want:
http://docs.hhvm.com/manual/en/hack.generics.php
I know this is not PHP. But it is compatible with it, and also improves your performance dramatically.
You can do it dirtily by passing the type as a second argument of the constructor
<?php class Collection implements IteratorAggregate{
private $type;
private $container;
public function __construct(array $collection, $type='Object'){
$this->type = $type;
foreach($collection as $value){
if(!($value instanceof $this->type)){
throw new RuntimeException('bad type for your collection');
}
}
$this->container = new \ArrayObject($collection);
}
public function getIterator(){
return $this->container->getIterator();
}
}
To provide a high level of static code-analysis, strict typing and usability, i came up with this solution: https://gist.github.com/rickhub/aa6cb712990041480b11d5624a60b53b
/**
* Class GenericCollection
*/
class GenericCollection implements \IteratorAggregate, \ArrayAccess{
/**
* #var string
*/
private $type;
/**
* #var array
*/
private $items = [];
/**
* GenericCollection constructor.
*
* #param string $type
*/
public function __construct(string $type){
$this->type = $type;
}
/**
* #param $item
*
* #return bool
*/
protected function checkType($item): bool{
$type = $this->getType();
return $item instanceof $type;
}
/**
* #return string
*/
public function getType(): string{
return $this->type;
}
/**
* #param string $type
*
* #return bool
*/
public function isType(string $type): bool{
return $this->type === $type;
}
#region IteratorAggregate
/**
* #return \Traversable|$type
*/
public function getIterator(): \Traversable{
return new \ArrayIterator($this->items);
}
#endregion
#region ArrayAccess
/**
* #param mixed $offset
*
* #return bool
*/
public function offsetExists($offset){
return isset($this->items[$offset]);
}
/**
* #param mixed $offset
*
* #return mixed|null
*/
public function offsetGet($offset){
return isset($this->items[$offset]) ? $this->items[$offset] : null;
}
/**
* #param mixed $offset
* #param mixed $item
*/
public function offsetSet($offset, $item){
if(!$this->checkType($item)){
throw new \InvalidArgumentException('invalid type');
}
$offset !== null ? $this->items[$offset] = $item : $this->items[] = $item;
}
/**
* #param mixed $offset
*/
public function offsetUnset($offset){
unset($this->items[$offset]);
}
#endregion
}
/**
* Class Item
*/
class Item{
/**
* #var int
*/
public $id = null;
/**
* #var string
*/
public $data = null;
/**
* Item constructor.
*
* #param int $id
* #param string $data
*/
public function __construct(int $id, string $data){
$this->id = $id;
$this->data = $data;
}
}
/**
* Class ItemCollection
*/
class ItemCollection extends GenericCollection{
/**
* ItemCollection constructor.
*/
public function __construct(){
parent::__construct(Item::class);
}
/**
* #return \Traversable|Item[]
*/
public function getIterator(): \Traversable{
return parent::getIterator();
}
}
/**
* Class ExampleService
*/
class ExampleService{
/**
* #var ItemCollection
*/
private $items = null;
/**
* SomeService constructor.
*
* #param ItemCollection $items
*/
public function __construct(ItemCollection $items){
$this->items = $items;
}
/**
* #return void
*/
public function list(){
foreach($this->items as $item){
echo $item->data;
}
}
}
/**
* Usage
*/
$collection = new ItemCollection;
$collection[] = new Item(1, 'foo');
$collection[] = new Item(2, 'bar');
$collection[] = new Item(3, 'foobar');
$collection[] = 42; // InvalidArgumentException: invalid type
$service = new ExampleService($collection);
$service->list();
Even if something like this would feel so much better:
class ExampleService{
public function __construct(Collection<Item> $items){
// ..
}
}
Hope generics will get into PHP soon.
One alternative is the combination of splat operator + typed hint + private array:
<?php
class Student {
public string $name;
public function __construct(string $name){
$this->name = $name;
}
}
class Classe {
private $students = [];
public function add(Student ...$student){
array_merge($this->students, $student);
}
public function getAll(){
return $this->students;
}
}
$c = new Classe();
$c->add(new Student('John'), new Student('Mary'), new Student('Kate'));

Java beans binding: adapters?

Here's a really simple class:
static public class Bean1
{
final private String name;
final private Bean1 parent;
private int favoriteNumber;
public String getName() { return this.name; }
public Bean getParent() { return this.parent; }
public int getFavoriteNumber() { return this.favoriteNumber; }
public void setFavoriteNumber(int i) { this.favoriteNumber = i; }
}
What I would like to do is to bind some UI components to a BeanAdapter<Bean1> (see com.jgoodies.binding.beans.BeanAdapter) so that if the BeanAdapter points to Bean1 bean1, then I can display
bean1.name (blank if null)
bean1.parent.name (blank if null or if bean1.parent is null)
bean1.favoriteNumber
The fields name and favoriteNumber are easy, but I'm confused about how to display the parent name. It looks like BeanAdapter only lets me bind to properties which exist directly in Bean1. But this is poor modularity and it forces me to add getter/setter functions every time I want to bind to a new aspect of the bean.
What I would like to do is write a helper class which knows how to access a bean, and am confused how to get it to work properly with Bean1 and BeanAdapter.
I'm sorry if this question is not more clear, I don't know the vocabulary and am a little hazy on the concepts of binding.
The problem here is that binding works in both ways: from model to ui, and from ui to model.
In your case, how would you deal with someone entering information for the first time in a textfield that's binded to parent.name? Would you create a parent on the fly? Would you give an error?
If you know what to do in that situation (e.g. create a parent with that name), you could use a com.jgoodies.binding.value.AbstractConverter to convert a Bean1 to a String:
public class ParentNameConverter extends AbstractConverter {
/**
* Converts a value from the subject to the type or format used
* by this converter.
*
* #param subjectValue the subject's value
* #return the converted value in the type or format used by this converter
*/
public Object convertFromSubject(Object subjectValue) { ... }
/**
* Sets a new value on the subject, after converting to appropriate type
* or format
*
* #param newValue the ui component's value
*/
public void setValue(Object newValue) { ... }
}
You can use this converter the same way you use a normal ValueModel:
Bindings.bind(uifield,"value",
new ParentNameConverter(beanAdapter.getValueModel("parent")));

Categories