DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Problems With Nested CompletableFuture in Java
  • Mastering Exception Handling in Java CompletableFuture: Insights and Examples
  • Proper Java Exception Handling

Trending

  • Solving Comprehension Debt in AI-Generated Codebases
  • PII Detection Before RAG Ingestion: Screening Documents in C#
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose
  • OpenCode: Setting Up an Open-Source AI Coding Assistant

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java Generics Wildcard Capture - A Useful Thing to Know

Java Generics Wildcard Capture - A Useful Thing to Know

By 
Shekhar Gulati
·
Jan. 20, 11 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
53.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Recently, I was writing a piece of code where I need to write a copy factory for a class. A copy factory is a static factory that will construct a copy of the same type as that of the argument passed to the factory. The copy factory will copy the state of the argument object into the new object. This will make sure that the newly constructed object is equal to the old one. A copy constructor is similar to a copy factory with just one difference - a copy constructor can only exist in the class containing the constructor whereas copy factory can exist in any other class as well. For example,

// Copy Factory
public static Field getNewInstance(Field field)
// Copy Constructor
public Field Field(Field field)

I choose static copy factory because

  • I didn't have the source code for the class
  • With copy factory I can code to an interface instead of a class.

The class for which I wanted to write copy factory was similar to the one shown below :

public class Field<T> {
private String name;
private T value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}

}

The first implementation of FieldUtils class that came to my mind was as shown below

public static Field<?> copy(Field<?> field) {
Field<?> objField = new Field<?>();//1
objField.setName(field.getName());//2
objField.setValue(field.getValue());//3
return objField;//4
}

The above code will not compile because of two compilation errors. The first compilation error is at line 1 because you can't create an instance of Field<?>.  Field<?> means Field<? extends Object> and when you have ? extends Something you can only get values out of it, you can't set values in it except null. For an object to be useful you should be able to do both, so the compiler does not allow you to create an object. The second compilation error will be at line number 3 and you will get a cryptic error message like this

The method setValue(capture#3-of ?) in the type Field<capture#3-of ?> is not applicable for the arguments (capture#4-of ?)

In simple terms this error message is saying that you are trying to set a wrong value in objField. But what if I had written the following method?

public static Field<?> copy(Field<?> field) {
field.setName(field.getName());
field.setValue(field.getValue());
return field;
}

Will the above code compile? No. You will again get a similar error message as mentioned above. To fix this error we will write a private helper method which will capture the wildcard and assign it to a Type variable. This technique is called Wildcard Capture. I have read this in the Java Generics and Collection book which is a must-read for understanding Java Generics. Wildcard Capture works by type inference.

public static Field<?> copy(Field<?> field) {
return copyHelper(field);
}

private static <T> Field<T> copyHelper(Field<T> field) {
Field<T> objField = new Field<T>();
objField.setName(field.getName());
objField.setValue(field.getValue());
return objField ;
}

Wildcard capture is very useful when you work with wildcards and knowing it will save a lot of your time.

Java (programming language) Factory (object-oriented programming) Error message

Opinions expressed by DZone contributors are their own.

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Problems With Nested CompletableFuture in Java
  • Mastering Exception Handling in Java CompletableFuture: Insights and Examples
  • Proper Java Exception Handling

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook