PMessageOrBuilder.java
/*
* Copyright 2015-2016 Providence Authors
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.morimekta.providence;
import net.morimekta.providence.descriptor.PField;
import net.morimekta.providence.descriptor.PMessageDescriptor;
import javax.annotation.Nonnull;
/**
* Base class for all messages and message builders.
*/
public interface PMessageOrBuilder<Message extends PMessage<Message>>
extends PValue<Message> {
/**
* @param key The key of the field.
* @return Whether the field is present.
*/
boolean has(int key);
/**
* @param key The key of the field.
* @param <T> The return type.
* @return The value of the field.
*/
<T> T get(int key);
/**
* @param field The field.
* @param <F> The message field type.
* @return Whether the field is present.
*/
default <F extends PField<Message>> boolean has(@Nonnull F field) {
return has(field.getId());
}
/**
* @param field The field.
* @param <T> The return type.
* @param <F> The message field type.
* @return Whether the field is present.
*/
default <T, F extends PField<Message>> T get(@Nonnull F field) {
return get(field.getId());
}
/**
* Cast the message or builder instance to it's instance, or build so
* it becomes a new instance from the builder.
*
* @return The message instance.
*/
@Nonnull
@SuppressWarnings("unchecked")
default Message toMessage() {
if (this instanceof PMessageBuilder) {
return ((PMessageBuilder<Message>) this).build();
}
return (Message) this;
}
/**
* Cast the message or builder instance to it's builder or mutate the instance
* so we have a fresh builder.
*
* @param <Builder> The builder type.
* @return The builder instance.
*/
@Nonnull
@SuppressWarnings("unchecked")
default <Builder extends PMessageBuilder<Message>>
Builder toBuilder() {
if (this instanceof PMessageBuilder) {
return (Builder) this;
}
return (Builder) ((Message) this).mutate();
}
@Nonnull
@Override
PMessageDescriptor<Message> descriptor();
}