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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

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

  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Four Essential Tips for Building a Robust REST API in Java
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  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 user avatar
Shekhar Gulati
·
Jan. 20, 11 · Interview
Likes (1)
Comment
Save
Tweet
Share
52.2K Views

Join the DZone community and get the full member experience.

Join For Free

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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!