com4j icon indicating copy to clipboard operation
com4j copied to clipboard

Unmarshal proper types for the elements of Collections ?

Open fjf2002 opened this issue 7 years ago • 1 comments

Is it possible to unmarshal proper types for the elements of Collections ?

Example: The generated Excel Workbooks interface implements Iterable<Com4jObject> instead of Iterable<_Workbook>. As far as I understand, I have to call .queryInterface(_Workbook.class) on each element manually:

for (final Com4jObject p : excel.getWorkbooks()) {
	System.out.println(p.queryInterface(_Workbook.class).getName());
}

Is it possible to get that conversion automagically? I think of something like the following...

  • I manually change the signatures of class Workbooks and its method iterator to the generic type _Workbook.

  • The above does not seem to be enough: My JVM dumps when I try that. So I think we need at least ComCollection's fetch method to call queryInterface to cast to the proper class?

fjf2002 avatar Feb 09 '18 14:02 fjf2002

My current ugly workaround is

for (final _Workbook p : iterableCaster(excel.getWorkbooks(), _Workbook.class)) {
	System.out.println(p.getName());
}

... with the method iterableCaster that simply adds a queryInterface call to the iterator.next call:

public static <T extends Com4jObject> Iterable<T> iterableCaster(
	final Iterable<Com4jObject> comIterable, final Class<T> clazz) {

	return new Iterable<T>() {

		@Override
		public Iterator<T> iterator() {
			return new Iterator<T>() {
				final Iterator<Com4jObject> delegate = comIterable.iterator();

				@Override
				public T next() {
					return delegate.next().queryInterface(clazz);
				}

				@Override
				public boolean hasNext() {
					return delegate.hasNext();
				}
			};
		}
	};
}

fjf2002 avatar Feb 09 '18 14:02 fjf2002